{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "MODEL_CACHE_DIR = r\"/share/LMs\"\n", "MODEL_NAME = \"lmsys/vicuna-13b-v1.5-16k\"" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2)\n", "(1, 3)\n", "(2, 3)\n" ] } ], "source": [ "from itertools import combinations\n", "\n", "for x in combinations([1, 2, 3], 2):\n", " print(x)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "2\n", "1\n" ] } ], "source": [ "for i in range(3, 0, -1):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Found cached dataset parquet (/share/peitian/Data/Datasets/huggingface/DKYoon___parquet/DKYoon--SlimPajama-6B-1735e67c45f712b7/0.0.0/14a00e99c0d15a23649d0db8944380ac81082d4b021f398733dd84f3a6c569a7)\n" ] }, { "data": { "text/plain": [ "Dataset({\n", " features: ['text', 'meta', '__index_level_0__'],\n", " num_rows: 5489000\n", "})" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import datasets\n", "\n", "dataset = datasets.load_dataset(\"DKYoon/SlimPajama-6B\", cache_dir=\"/share/peitian/Data/Datasets/huggingface\", split=\"train\")\n", "\n", "dataset" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ " 0%| | 0/5489000 [00:00 27112)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Dataset({\n", " features: ['text', 'meta', '__index_level_0__'],\n", " num_rows: 10785\n", "})" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "paper" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\\\section{INTRODUCTION}\\nMicroquasars are well known miniatures of quasars, with a central\\nblack hole (BH), an accretion disk and two relativistic jets very\\nsimilar to those found in the centers of active galaxies, only on\\nmuch smaller scales (Mirabel $\\\\&$ Rodr\\\\\\'{\\\\i}guez 1999). The typical\\ntimescales in these systems are also $10^{5}-10^{7}$ times shorter\\nthan those in quasars, thus evolutions of microquasar jets can be\\nstudied in details. Therefore, microquasar systems have been\\nconsidered ideal laboratories for understanding accretion process in\\nblack hole systems and might provide us a good alternative to study\\nAGN phenomena instead of observing them directly (Massi \\\\& Kaufman\\nBernad\\\\\\'o 2008).\\n\\nSince discovered in 1992, radio jets have been observed in a series\\nof BH binary systems and several of them showed apparent\\nsuperluminal features. In the two well known microquasars, GRS\\n1915+105 (Mirabel $\\\\&$ Rodr\\\\\\'{\\\\i}guez 1999) and GRO J1655-40 (Tingay\\net al. 1995; Hjellming $\\\\&$ Rupen 1995), relativistic jets with\\nactual velocities greater than 0.9$c$ were observed. In some other\\nsystems, small-size ``compact jets\", e.g. Cyg X-1 (Stirling et al.\\n2001), and large scale diffuse emission, e.g. SS433 (Dubner et al.\\n1998), were also detected.\\n\\nAmong these microquasars, XTE J1550-564 is especially interesting\\nsince it was the first Galactic accretion systems that a fast moving\\nX-ray jet was detected. The large scale and long existing time of\\nthe jets have also made this source unique and valuable in jet\\nstudies. XTE J1550-564 was discovered with RXTE in 1998 during its\\nstrong X-ray outburst on September 7 (Smith 1998). It is believed to\\nbe an X-ray binary system at a distance of $\\\\sim$5.3 kpc, containing\\na black hole of 10.5$\\\\pm$1.0 solar masses and a low mass companion\\nstar (Orosz et al. 2002). Soon after the discovery of the source, a\\njet ejection with an apparent velocity greater than 2$c$ was\\nreported by VLBI team (Hannikainen et al. 2001). In the period\\nbetween 1998 and 2002, the source also exhibited strong X-ray\\nactivities but no similar radio and X-ray flares were detected again\\nduring these activities (Tomsick et al. 2003).\\n\\nWith the $\\\\it Chandra$ satellite, Corbel et al. (2002) found two\\nlarge scale X-ray jets lying to the east and west of the central\\nsource, which were also in good alignment with the central source.\\nThe eastern jet has been detected first in 2000 at a projected\\ndistance of $\\\\sim$21 arcsec and a position angle E of N of\\n93.8$\\\\textordmasculine\\\\pm$0.9$\\\\textordmasculine$ from the central\\nblack hole. Its apparent proper motion velocity has dropped from an\\naverage of $\\\\sim$32.9 mas/day between 1998 and 2000 to $\\\\sim$21.2\\nmas/day during its 2000 observations; its X-ray flux also decayed\\nquite rapidly. Two years later, it could only be seen marginally in\\nthe X-ray image, while a western counterpart became visible at\\n$\\\\sim$22 arcsec on the other side. The corresponding radio maps are\\nconsistent with the X-ray observations (Corbel et al. 2002).\\n\\nFrom the year 2002 to 2003, there were altogether five observations\\nof this source in the $\\\\it Chandra$ archive. The eastern jet has\\ndisappeared from the X-ray images in late 2002, while the western\\njet could be seen clearly in all the five observations, although the\\nflux decayed quickly as well. Among these observations, only the\\nfirst two have been reported and discussed previously (Kaaret et al.\\n2003; Wang et al. 2003). We therefore use these additional data\\npoints to better constrain the kinematic and spectral analysis for\\nthe eastern jet, and to extend the analysis to the western jet.\\n\\nIn this paper, we first describe the observational data obtained by\\n$\\\\it Chandra$ X-ray satellite in section 2 and 3. Then we propose a\\nmodel for the system and discuss the kinematic and emission process\\nin section 4. Finally in section 5 and 6, we apply this model to\\nanother source H 1743-322 and make some further discussions based on\\nthese analysis.\\n\\n \\\\placetable{table1}\\n\\n\\\\begin{deluxetable}{rrrrrrrr}\\n\\\\tabletypesize{\\\\footnotesize} \\\\tablecolumns{8} \\\\tablewidth{0pc}\\n\\\\tablecaption{XTE J1550-564 $\\\\it Chandra$\\nObservations\\\\label{table1}} \\\\tablehead{ \\\\colhead{} & \\\\colhead{} &\\n\\\\colhead{} & \\\\colhead{} & \\\\multicolumn{2}{c}{Eastern Jet} &\\n\\\\multicolumn{2}{c}{Western Jet} \\\\\\\\\\n\\\\cline{5-8}\\\\\\\\\\n\\\\colhead{Obs} & \\\\colhead{Obs} & \\\\colhead{Obs} & \\\\colhead{Exposure}\\n & \\\\colhead{RA} & \\\\colhead{Dec} &\\n\\\\colhead{RA} & \\\\colhead{Dec} \\\\\\\\\\n\\\\colhead{Num} & \\\\colhead{ID} & \\\\colhead{date} & \\\\colhead{(s)} &\\n\\\\colhead{(15:51:)} & \\\\colhead{ (-56:28:)} & \\\\colhead{(15:50:)} &\\n\\\\colhead{(-56:28:)}}\\n\\n\\\\startdata\\n1 &679 & 2000 Jun 9 &3816 &01.\\\\tablenotemark{a} &36.7 & & \\\\\\\\\\n2 &1845 & 2000 Aug 21 &5160 &01.4$\\\\pm$2$\\\\times$10$^{-2}$ & 36.7$\\\\pm$1$\\\\times$10$^{-2}$ & & \\\\\\\\\\n3 &1846 & 2000 Sep 11 &4630 &01.5$\\\\pm$2$\\\\times$10$^{-2}$ & 36.6$\\\\pm$1$\\\\times$10$^{-2}$ & & \\\\\\\\\\n4 &3448 & 2002 Mar 11 &26118 &02.1$\\\\pm$1$\\\\times$10$^{-2}$ & 37.4$\\\\pm$1$\\\\times$10$^{-2}$ & 56.0$\\\\pm$4$\\\\times$10$^{-3}$ & 33.5$\\\\pm$2$\\\\times$10$^{-3}$\\\\\\\\\\n5 &3672 & 2002 Jun 19 &18025 & & & 55.9$\\\\pm$4$\\\\times$10$^{-3}$ & 33.7$\\\\pm$2$\\\\times$10$^{-3}$ \\\\\\\\\\n6 &3807 & 2002 Sep 24 &24442 &02.17\\\\tablenotemark{b} & 37.6 &55.86$\\\\pm$6$\\\\times$10$^{-3}$ & 33.9$\\\\pm$3$\\\\times$10$^{-3}$\\\\\\\\\\n7 &4368 & 2003 Jan 28 &23680 & & & 55.82$\\\\pm$6$\\\\times$10$^{-3}$ &33.6$\\\\pm$4$\\\\times$10$^{-3}$ \\\\\\\\\\n8 &5190 & 2003 Oct 23 &47831 & & &55.74$\\\\pm$6$\\\\times$10$^{-3}$\\n&33.6$\\\\pm$3$\\\\times$10$^{-3}$\\n \\\\enddata\\n\\\\tablenotetext{a}{Positions of the eastern and the western jets are\\ncorrected after calibration of the central source to the position of\\nthe radio observation as RA = 15:50:58.71 and DEC = -56:28:35.7\\n(Corbel et al. 2001) and the positions are subject to the 0.3 arcsec\\npositional uncertainty found by Corbel et al. (2001) on their radio\\nposition. The quoted errors are the statistical errors provided by wavdetect. However, $wavdetect$ did not provide error information\\nfor observation 1.} \\\\tablenotetext{b}{The position of the eastern\\njet in observation 6 is determined by the center of the strongest\\nemission region, as marked by a small circle on fig 2.}\\n\\n\\\\end{deluxetable}\\n\\n\\n\\\\section{OBSERVATIONS of XTE J1550-564}\\nThere are altogether eight 2-dimensional imaging observations of XTE\\nJ1550-564 in the $\\\\it Chandra$ archive during June 2000 and October\\n2003 (henceforth observations 1$\\\\sim$8). These observations were all\\nmade by the Advanced CCD Imaging Spectrometer (ACIS). There are also\\ngrating observations providing 1-dimensional imaging in the archive;\\nbut since our interests are in the jet kinematics analysis, these\\nare not our focus at this stage.\\n\\nWe have down-loaded all data of these eight observations from the\\narchive and examined the level 2 event files produced by Standard\\nData Processing procedures to make our analysis. Exposure time for\\nthese observations ranges from a few kiloseconds (observations\\n1$\\\\sim$3) to a few tens of kiloseconds (observations 4$\\\\sim$8)\\n(Table 1). Background light curves are extracted for each of the\\nobservations and only in observation 5 a high background flare is\\ndetected. Except for this period, almost all valid exposure time\\nintervals of these observations are included in our work.\\n\\nIn the section 2 and 3, we limit most of our analysis to the\\nkinematic and spectral properties of the western jet. The central\\naccreting source has already attracted much attention in recent\\nyears and there were already plenty of studies in details in\\nliterature (Corbel et al. 2001; Jain et al. 2001; Kubota $\\\\&$\\nMakishima 2004; Yuan et al. 2007). The eastern jet has also been\\nstudied fully in 2003 when it was discovered (Tomsick et al. 2003;\\nKaaret et al. 2003). As a result, we do not discuss much of our\\nresults for observations 1$\\\\sim$3 here; only comparisons with the\\nprevious works will be noted for consistency. A complete study of\\nthe kinematic and light curve evolution of the western jet is our\\nmain goal in these two sections.\\n\\nWe list the basic information of observations 1$\\\\sim$8 in Table 1,\\nincluding the observation ID, date, the positions of the central\\npoint source and the eastern and western jets respectively (in J2000\\ncoordinate). The positions are obtained by the $\\\\it Chandra$\\nInteractive Analysis of Observations (CIAO) routine $wavdetect$\\n(Freeman et al. 2002), a commonly used program in determining X-ray\\nsources in $\\\\it Chandra$ images. From this table, we could see\\nclearly that an X-ray emission source is detected to the east of the\\ncentral source in the first four observations and another source is\\ndetected to the west in the last five observations. Calculations\\nalso show that these two sources, when presented in a single\\ncombined image, are in good alignment with the central compact\\nobject with a position angle E of N of -85.9\\\\textordmasculine\\n$\\\\pm$0.3\\\\textordmasculine . In observations 5 and 6, no X-ray source\\nis detected by $wavdetect$ at the position of the eastern jet.\\nHowever, from the Gaussian smoothed images (Fig. 2), a weak source\\ncould be recognized in observation 6. We thus select the strongest\\nemission region of this source manually with a small circle of the\\nradius of 0.7 arcsec and use the position of its center as one data\\npoint in our further analysis.\\n\\nIn Fig.1, the raw, unsmoothed images of the last five observations\\nare shown. An extended and moving source can be seen easily in these\\nimages. Its elongation points towards the central source, and has\\nthus indicated clearly the relation between them. In most cases the\\nflux from this western source is comparable to the central source;\\nhowever in observation 5, the observed surface brightness from the\\nwestern source is even higher than the central source (also see\\nsection 3).\\n\\n\\n\\\\placefigure{fig1}\\n\\\\begin{figure}\\n\\\\includegraphics[width=10cm]{f1.eps}\\n\\\\caption{The $\\\\it Chandra$ 0.3-8 keV raw image showing XTE J1550-564\\nand the western jet. The images are in linear scale and no count\\nsaturation has been set. Each image is normalized to its own color\\nscale. The color bar below the images indicates the relative\\nstrength. The numbers under the color bar indicate the number of\\nphotons in each pixel for the first image (obs 4, ID=3448), and the\\npeak count values in the other four images (obs 5-8) are 27, 60, 58,\\n36, respectively. The pixel size is $0\".492\\\\times0\".492$. The green\\ncircle in each observation shows the spectral extraction region for\\neach jet, which is of 8 arcsec in diameter and includes almost all\\nof the jet counts (albeit that there is no guarantee that all jet\\nphotons are included, due to the wing of the point spread function\\nof the {\\\\it $\\\\it Chandra$} mirror assembly.). The images are aligned\\nby RA (x-axis).} \\\\label{fig1}\\n\\\\end{figure}\\n\\n\\\\placefigure{fig2}\\n\\\\begin{figure}\\n\\\\includegraphics[width=10cm]{f2.eps}\\n\\\\caption{The smoothed $\\\\it Chandra$ X-ray images of the eight\\nobservations of XTE J1550-564 and the two jets together. Except for\\nthe first observation, in which the central BH is too bright so a\\nlog scale is set to reveal the eastern jet, all the images are in\\nlinear scale and no count saturation has been set. The appearance\\nand disappearance of the eastern and western jets can be seen\\nclearly in the image. Each image is normalized to its own color\\nscale. The color bar below the images indicates the relative\\nstrength. The numbers under the color bar indicate the number of\\nphotons in each pixel for the fourth image (obs 4, ID=3448) (to be\\nconsistent with fig. 1), and the peak count values in the other\\nseven images (obs 1-3, 5-8) are 18.8, 3.8, 6.3, 10.3, 13.4, 15.2,\\n9.0, respectively. The green elliptical regions are source emission\\nregions detected by {\\\\it wavdetect}. Observation 4 shows the good\\nalignment of the two jets and the central source. The images are\\naligned by RA (x-axis).}\\n \\\\label{fig2}\\n\\\\end{figure}\\n\\n\\nWith the data in Table 1, we can calculate the angular separations\\nbetween the jets and the central source as well as the average\\nproper motions. In this paper, we have adopted the assumption that\\nboth the eastern and western jets are related to the same outburst\\nin September 1998. Except for the outburst occurred in 1998, there\\nwere some other outbursts detected afterwards, including a major\\noutburst in 2000 and some mini-outbursts in 2001 to 2003 (Tomsick et\\nal. 2003 and references therein). However, the long term RXTE-ASM\\nlight curve shows that the X-ray flux of the 1998 outburst is four\\ntimes higher than that of the 2000 outburst and more than twenty\\ntimes higher than that of all the rest (Sturner $\\\\&$ Shrader 2005).\\nThe complex behaviors found in the 1998 outburst, such as irregular\\nlight curves and multiple state transitions, were not detected in\\nother outbursts. The two X-ray jets are also found to be aligned\\nwith the 1998 radio jets (Corbel et al. 2002), which is also\\nconsistent with the assumption of a common origin of the two jets,\\nbut by itself does not provide definite evidence for the assumption\\nunless the source is precessing strongly. Based on the above\\narguments, we conclude that it is reasonable to assume that both the\\neastern and western jets originated from the same 1998 outburst.\\n\\nOur calculation results are listed in Table 2. A distance of\\napproximately 23 arcsec is obtained for the western jet with a\\nslowly increasing value; errors are estimated following the method\\ndescribed by Tomsick et al. (2003). We calculate the source centroid\\nfor the central source and the X-ray jet respectively and for all\\nthe five observations, the changes of the newly calculated position\\nwith the previous results are less than 0.5\\\\arcsec. Therefore, an\\nupper limit of 0.5\\\\arcsec is set for the error of the jet distance\\n(except the eastern jet in observation 6, where a larger error of 1\\narcsec was set because of the manual selection method we applied).\\nWe divide the net angular separation by the time interval between\\nthe neighboring observations to estimate the average proper motion\\nfor the jets, and from the results, an approximate estimate of\\ndeceleration could be seen for both jets. The absolute astrometry of\\nChandra is calibrated by fixing the X-ray position of the central\\nsource as its radio position reported by Corbel et al (2001).\\n\\n\\\\placetable{table2}\\n\\n\\\\begin{deluxetable}{rrrrrrr}\\n\\\\tabletypesize{\\\\footnotesize} \\\\tablecolumns{7} \\\\tablewidth{0pc}\\n\\\\tablecaption{Angular Separations and Proper Motions of the Eastern\\nand Western Jets\\\\label{table2}} \\\\tablehead{ \\\\colhead{} & \\\\colhead{}\\n& \\\\colhead{Time after} & \\\\multicolumn{2}{c}{Separations to the BH\\n(arcsec)\\\\tablenotemark{a}} &\\n\\\\multicolumn{2}{c}{Average Proper Motion (mas/d)\\\\tablenotemark{b}} \\\\\\\\\\n\\\\cline{4-5} \\\\cline{6-7}\\\\\\\\\\n\\\\colhead{Obs Num} & \\\\colhead{Obs ID} & \\\\colhead{X-ray burst\\n(days)} & \\\\colhead{Eastern Jet} & \\\\colhead{Western jet} &\\n\\\\colhead{Eastern Jet} & \\\\colhead{Western jet} }\\n\\n \\\\startdata\\n1 &679 & 628 &21.5$\\\\pm$0.5 & &33.9$\\\\pm$0.8 & \\\\\\\\\\n2 &1845 & 700 &22.8$\\\\pm$0.5 & &21.1$\\\\pm$0.7 & \\\\\\\\\\n3 &1846 & 720 &23.4$\\\\pm$0.5 & &31.5$\\\\pm$0.7 & \\\\\\\\\\n4 &3448 & 1265 &28.6$\\\\pm$0.5 &22.6$\\\\pm$0.5 &9.4$\\\\pm$0.4 &17.9$\\\\pm$0.4\\\\\\\\\\n5 &3672 & 1365 & &23.2$\\\\pm$0.5 & &6.3$\\\\pm$0.4 \\\\\\\\\\n6 &3807 & 1462 &29.2$\\\\pm$1.4 &23.4$\\\\pm$0.5 & 3.3$\\\\pm$0.3 &1.6$\\\\pm$0.3\\\\\\\\\\n7 &4368 & 1588 & &23.7$\\\\pm$0.5 & &2.2$\\\\pm$0.3 \\\\\\\\\\n8 &5190 & 1856 & &24.5$\\\\pm$0.5 & &3.2$\\\\pm$0.3\\n \\\\enddata\\n\\n\\\\tablenotetext{a}{Errors are estimated by following Tomsick et al.\\n(2003).} \\\\tablenotetext{b}{Values obtained by dividing the net\\nangular separation and the error by the time interval between the\\nneighboring observations.} \\\\tablenotemark{c}{The error bar of the angular separation of the eastern jet in observation 6\\nis estimated as 2 times the radius of the circle.}\\n\\n\\\\end{deluxetable}\\n\\n\\n\\\\section{ENERGY SPECTRUM and FLUX}\\n\\nWe extract the X-ray spectrum in 0.3-8 keV energy band for each\\nobservation. To be consistent with previous analysis of the eastern\\njet, we follow some of those previous procedures. Because of the\\nmuch longer exposure time, the total counts collected from each of\\nthe last five observations are much more than those from the first\\nthree. We use a circular source region with a radius of 4\\\\arcsec, an\\nannular background region with an inner radius of 5\\\\arcsec and an\\nouter radius of 15\\\\arcsec, for each observation. The photon number\\ninside each selected region is about a few hundreds, possible for\\nspectral analysis, compared to only $\\\\sim$20 counts in the jet\\nregion in observations 1, 2 and 3. We perform background subtraction\\nbut did not make independent background spectra.\\n\\nInstrument response matrices (rmf) and weighted auxiliary response\\nfiles (warf) are created using CIAO programs {\\\\it mkacisrmf} and\\n{\\\\it mkwarf} and used in the fitting in {\\\\it Xspec}. We re-bin the\\nspectra with 10 counts per bin and fit them in {\\\\it Xspec}. Several\\nspectral models are tested, but the statistical quality is not high\\nenough to distinguish between them completely. Taking observation 4\\nfor example (for the reason that the photon number of this\\nobservation is the largest), synchrotron model (powerlaw) and self\\nCompton scattering (compsl) seem to work equally well with the\\ncorresponding reduced $\\\\chi^{2}$ of 0.924 and 0.925. Their\\ncombination (powerlaw+compsl) does not improve the fitting\\n($\\\\chi^{2}\\\\sim0.981$), but creates a large uncertainty for each\\nparameter (the best fitting photon index is $2\\\\pm28$ in the combined\\nmodel).\\n\\nIn table 3, the results of spectra fitting to the western jet with\\nan absorbed power-law model are shown (spectra shown in Fig. 3). The absorption column density\\nis fixed to the Galactic value in the direction of XTE J1550-564\\nobtained by the radio observations ($N_{H}=9\\\\times10^{21}$cm$^{-2}$)\\n(Dickey \\\\& Lockman 1990). The first two observations (obs. 4 $\\\\&$ 5)\\nhave been analyzed by Kaaret et al. (2003), and our results are\\nquite consistent with their work. The mean photon index of the five\\nobservations is around 1.8, also consistent with the previous work\\non the eastern jet (Tomsick et al. 2003). A slightly different\\nphoton index is obtained for observation 6 and 8; however, the value\\nof 1.8 is still within the 1-$\\\\sigma$ error range. The calculated\\nabsorbed energy flux in 0.3-8 keV band is comparable to the value of\\nthe eastern jet. The observed flux decayed from\\n$\\\\sim1.9\\\\times10^{-13}$ erg cm$^{-2}$ s$^{-1}$ in March 2002 to only\\none sixth of this value in October 2003 (see section 4.2). For\\nobservation 6, we also try to fit the spectrum of the eastern jet.\\nHowever, the data points are just too few to yield a satisfactory\\nresult. With only 17 counts between 0.3 to 10 keV inside a\\n8-arcsec-diameter circle, we obtained a reduced $\\\\chi^{2}$ of only\\n0.13 when using the chi-squared statistic in fitting. When changing\\nto the Cash statistic, a more suitable method for low counts cases,\\nthe resulting photon index is 1.11 and the estimated flux is\\n1.6$\\\\times$10$^{-14}$ erg cm$^{-2}$ s$^{-1}$, even higher than the\\nvalue in observation 4. We consider this result not very convincing,\\nor the re-heating process is more complicated than a simple shock.\\nComplete understanding of this problem is beyond the scope of the\\ncurrent work. As a result, we drop this spectral data point in the\\nlight curve fitting.\\n\\n\\\\placetable{c}\\n\\n\\\\placefigure{fig3}\\n\\\\begin{figure}\\n\\\\includegraphics[height=18cm]{f3.eps}\\n \\\\caption{X-ray spectra of emission from the\\nwestern jet during March 2002 and October 2003. The five panels are\\ndata from observations 4$\\\\sim$8 respectively. An absorbed power-law\\nmodel with the neutral hydrogen column density fixed to the Galactic\\nvalue, $9\\\\times10^{21}$cm$^{-2}$, is used in the fitting. Values of\\nall fitted parameters are listed in Table 3.}\\n \\\\label{fig3}\\n\\\\end{figure}\\n\\n\\\\placetable{table3}\\n\\n\\\\begin{deluxetable}{rrrrrrr}\\n\\\\tabletypesize{\\\\footnotesize} \\\\tablecolumns{7} \\\\tablewidth{0pc}\\n\\\\tablecaption{Spectral Properties of the Western Jet\\\\label{table3}}\\n\\\\tablehead{ \\\\colhead{} & \\\\colhead{} & \\\\colhead{} & \\\\colhead{} &\\n\\\\multicolumn{3}{c}{Powerlaw Fitting\\nResults\\\\tablenotemark{a}} \\\\\\\\\\n\\\\cline{5-7}\\\\\\\\\\n\\\\colhead{Obs Num}& \\\\colhead{Time after X-ray} & \\\\colhead{Total\\nCounts} & \\\\colhead{Counts Rate} & \\\\colhead{Photon} &\\n\\\\colhead{Reduced}\\n& \\\\colhead{Flux\\\\tablenotemark{b}}\\\\\\\\\\n\\\\colhead{}& \\\\colhead{burst (days)} & \\\\colhead{(0.3-8 keV)} &\\n\\\\colhead{(cts/s)} & \\\\colhead{Index} &\\\\colhead{$\\\\chi^{2}$}&\\n\\\\colhead{ergs cm$^{-2}$ s$^{-1}$} }\\n\\n \\\\startdata\\n4 &1265 &419 &0.016 &1.75$\\\\pm$0.11 &0.91 &$(1.9\\\\pm0.4)\\\\times10^{-13}$\\\\\\\\\\n5 &1355 &248 &0.014 &1.71$\\\\pm$0.15 &0.91 &$(1.6\\\\pm0.3)\\\\times10^{-13}$\\\\\\\\\\n6 &1462 &197 &0.008 &1.94$\\\\pm$0.17 &0.90 &$(8.6\\\\pm1.5)\\\\times10^{-14}$\\\\\\\\\\n7 &1588 &114 &0.005 &1.81$\\\\pm$0.22 &0.80 &$(5.5\\\\pm1.0)\\\\times10^{-14}$\\\\\\\\\\n8 &1856 &137 &0.003 &1.97$\\\\pm$0.20 &1.76 &$(3.1\\\\pm0.6)\\\\times10^{-14}$\\\\\\\\\\n \\\\enddata\\n\\n\\\\tablenotetext{a}{Absorbed Powerlaw model with fixed $N_{\\\\rm\\nH}=9\\\\times10^{21}$ cm$^{-2}$.} \\\\tablenotetext{b}{Absorbed flux in\\n0.3-8 keV band.}\\n\\n\\\\end{deluxetable}\\n\\n\\\\section{JET MODEL}\\n\\nWe now describe the model of Wang et al. (2003), and apply it to the\\ndata, demonstrating how it needs to be revised to fit the full set\\nof observations of the eastern and western jets. The kinematic and\\nlight curve models are constructed according to the external shock\\nmodel in the standard gamma-ray burst (GRB) afterglow theory. In\\nthis model, the kinematic evolution and light curve of the jets can\\nbe interpreted by the interactions between the jet materials and the\\ninterstellar medium (ISM). The relativistic ejecta losses its energy\\nto the ISM and is therefore slowed down to non-relativistic phase.\\nIn Wang et al. (2003), they used the reverse shock emission model to\\nfit the light curve of the eastern jet successfully. We therefore\\napply this model to the analysis of the western jet as well.\\n\\n\\\\subsection{Kinematic Model}\\n\\nAs we know, in the external shock model for afterglows of GRBs, the\\nkinematic and light curve evolution could be understood as the\\ninteraction between the outburst ejecta and the surrounding ISM\\n(Rees \\\\& M\\\\\\'{e}sz\\\\\\'{a}ros 1992). Since microquasar systems are also\\nGalactic sources embedded inside the ISM, we may infer that the jets\\nof microquasars should also encounter such interactions and thus be\\ndecelerated during their expansion. The large scale and long\\nexisting time of XTE J1550-564 jets have provided us a good\\nopportunity to test this scenario.\\n\\nBecause of the good alignment of the two jets and the central\\naccreting object, we adopt the model of a collimated conical beam\\nwith a half opening angle $\\\\theta_{j}$ expanding into the ambient\\nmedium with the number density $n$. The initial kinematic energy and\\nLorentz factor of the outflow material are $E_{0}$ and $\\\\Gamma_{0}$,\\nrespectively. Shocks should arise as the outflow moves on and heat\\nthe ISM, and its kinematic energy will turn into the internal energy\\nof the medium gradually. Neglect the radiation loss, the energy\\nconservation equation writes (Huang, Dai, \\\\& Lu 1999):\\n\\\\begin{equation}\\\\label{a}\\n(\\\\Gamma-1)M_{0}c^{2}+\\\\sigma(\\\\Gamma_{\\\\rm{\\\\tiny sh}}^{2}-1)m_{\\\\rm{\\\\tiny SW}}c^{2}=E_{0}.\\n\\\\end{equation}\\n\\nThe first term on the left of the equation represents the kinematic energy of the\\nejecta, where $\\\\Gamma$ is the Lorentz factor and $M_{0}$ is the mass of the original\\nejecta. The second term represents the internal energy of the swept-up ISM, where\\n$\\\\Gamma_{\\\\rm{\\\\tiny sh}}$ and $m_{\\\\rm{\\\\tiny SW}}$ are the corresponding Lorentz Factor\\nand mass of the shocked ISM respectively, and\\n\\\\begin{equation}\\\\label{a}\\nm_{\\\\rm{\\\\tiny SW}}=V_{\\\\rm g}m_{\\\\rm p}n(\\\\theta_{j}^{2}/4),\\n\\\\end{equation}\\nwith $V_{\\\\rm g}$ as the shocked gas volume. Coefficient $\\\\sigma$ differs from 6/17 to 0.73 for\\nultra-relativistic and non-relativistic jets (Blandford \\\\& McKee 1976). Wang et al. (2003) took $\\\\sigma\\\\sim$0.7\\nand we adopt their approximation in our work. Equation (1) and the relativistic kinematic equations\\n\\\\begin{equation}\\n(\\\\frac{dR}{dt})_{\\\\rm{a}}=\\\\frac{\\\\beta(\\\\Gamma)c}{1-\\\\beta(\\\\Gamma)\\\\cos\\\\theta};\\n(\\\\frac{dR}{dt})_{\\\\rm{r}}=\\\\frac{\\\\beta(\\\\Gamma)c}{1+\\\\beta(\\\\Gamma)\\\\cos\\\\theta}\\n\\\\end{equation}\\ncan be solved and give the relation between the projected angular\\nseparation $\\\\mu$ and time $t$. In equations (2), the subscript `a\\'\\nand `r\\' represent the approaching and receding jets in a pair of\\nrelativistic jets respectively. $R$ is the distance between the jet\\nand the source, which can be transformed into the angular separation\\nby $\\\\mu=R\\\\sin\\\\theta/5.3$ kpc, and $\\\\theta$ is the jet inclination\\nangle to the line of sight. We can get the $\\\\mu-t$ curve numerically\\nwith the above equations. To be consistent with the work done to the\\neastern jet, we test first the same initial conditions that\\n$\\\\Gamma_{0}=3$, $E_{0}=3.6\\\\times10^{44}$ erg,\\n$\\\\theta=50\\\\textordmasculine$ and $\\\\theta_{j}=1.\\\\textordmasculine5$\\nas those found by Wang et al. (2003) and would like to find how\\nthese parameters affect the fitting of the jet motions.\\n\\nIn the case of the eastern jet, the number density of the ISM was\\nassumed by Wang et al. (2003) as a constant in the whole region\\noutside the central source, thus the interaction was supposed to\\nhave taken place all the way along the jet\\'s path. This assumption\\ndoes not work well in the case of its western counterpart, because\\nthe western jet has traveled by 2002 as far as the eastern jet had\\ntraveled by 2000, but was decelerated much more significantly. This\\ncan be seen in Fig. 4. The western jet moved comparatively little\\nafter its appearance and acted like ``hitting into a wall\". This\\nrequires much stronger interactions and thus a much denser\\nenvironment. We tried to fit the western jet itself but were not\\nvery successful. If we increase the number density, the gas will\\nsimply block the jet and the jet will never travel to such a far\\ndistance (a 10$^{44}$ erg jet can only move to $\\\\sim$7-8 arcsec in 1\\ncm$^{-3}$ ISM). On the other hand, if the initial energy is too\\nlarge ($\\\\sim$10$^{50}$ erg), the jet could penetrate ISM and travel\\nfar but would be very difficult to slow down so quickly (for such\\nhigh energy, even a density of 100 cm$^{-3}$ can not bend the curve\\ndown). Changing the initial Lorentz factor has similar results with\\nchanging initial energy and the opening angle of the jet affects the\\nresults quite little. This tendencies are plotted in Fig.4 (a),\\nwhere the fitting to the eastern jet shows the model of Wang et al.\\n(2003) and the corresponding solid-line fitting to the western jet\\nuses the same model and same parameters. The dashed line and dot\\ndashed line there represent the results of changing the number\\ndensity or the initial kinetic energy to ten times of the eastern\\nresults. All three curves do not match the data points well.\\n\\nAs a result, we consider keeping the initial Lorentz factor and\\nenergy, while changing the geometric assumptions to describe the jet\\nmotions. For the inclination angle, we first examined the paper of\\nOrosz et al. (2002), where they find a value of 72.6 $\\\\pm$\\n4.8$\\\\textordmasculine$ from the optical observations. We took this\\nvalue, but varying it within their 1-sigma error bars, and find\\n$\\\\theta=68\\\\textordmasculine$ gives out the best fit. To simplify the\\nproblem, we just fix the inclination angle to this value in our\\nwork.\\n\\nAfter setting the inclination angle, we test a model that the ISM\\ndensity varies as the distance changes, i.e., the density is lower\\nin the center and higher in the outside region. For simplicity, we\\ntest the case that the jet traveled first through a ``cavity\" with a\\nconstant velocity and then through a dense region and was\\ndecelerated there. For this modification, we introduce another\\nparameter $r$, the outer radius of the cavity. The ISM number\\ndensity is set to be a constant $n$ outside this region and zero\\ninside. The results are shown in panel (b) and (c) in Fig.4. We\\nfirst apply this model to the eastern and the western jet\\nseparately. The results are quite satisfactory but not well\\nconstrained. Because of only 10 data points in constraining 4 free\\nparameters ($r_{\\\\rm{e}}$, $r_{\\\\rm{w}}$, $n_{\\\\rm{e}}$, $n_{\\\\rm{w}}$),\\nthere are more than one group of parameters that seem work well.\\nFitting the two jets simultaneously with a fixed cavity radius helps\\na bit. It constrains the fitting tighter and $r=16$ arcsec seems an\\nacceptable result for the both sides (Fig.4 (b)). However, this is\\nnot a sound assumption. The inferred ISM number density\\ncorresponding to this value is 0.015 cm$^{-3}$ in the east and 0.06\\ncm$^{-3}$ in the west respectively, indicating a clear asymmetry in\\nthe ISM density on the two side. Thus it is not reasonable to assume\\na perfect symmetric geometry. We still need other analysis to help\\ndetermining consistent parameters.\\n\\n \\\\placefigure{fig4}\\n\\\\begin{figure}\\n\\\\includegraphics[width=9cm,,height=18cm]{f4.eps}\\n\\\\caption{Model fittings to the proper motion of the X-ray jets of\\nXTE J1550-564. In all three panels, the pink lines are the model\\npredictions of the approaching jet and the blue lines are models\\npredictions of the receding jet. Panel (a):\\n$\\\\theta$=50\\\\textordmasculine , $n_{0}=1.5\\\\times10^{-4}$ cm$^{-3}$,\\n$E_{0}=3.6\\\\times10^{44}$ erg and $r_{\\\\rm{e}}$=$r_{\\\\rm{w}}$=0.\\nFitting to the approaching jet is the model from Wang et al. (2003).\\nThe model for the western jet is based on the same parameters. The\\ndashed and dotted lines are the results if the number density or the\\ninitial kinematic energy is changed to ten times of the eastern\\nresults. Panel (b): model with a symmetric cavity introduced.\\nParameters: $\\\\theta$=68\\\\textordmasculine,\\n$r_{\\\\rm{e}}$=$r_{\\\\rm{w}}$=16 arcsec, $n_{\\\\rm{e}}$=0.015 cm$^{-3}$,\\n$n_{\\\\rm{w}}$=0.06 cm$^{-3}$. Panel (c): model with an asymmetric\\ncavity introduced. Parameters: $\\\\theta$=68\\\\textordmasculine,\\n$r_{\\\\rm{e}}$=12 arcsec, $r_{\\\\rm{w}}$=17 arcsec, $n_{\\\\rm{e}}$=0.0034\\ncm$^{-3}$, $n_{\\\\rm{w}}$=0.12 cm$^{-3}$.} \\\\label{fig4}\\n\\\\end{figure}\\n\\n\\\\subsection{Light Curve Model}\\nIn the standard GRB scenario, the afterglow emission is produced by\\nthe synchrotron radiation or inverse Compton emission of the\\naccelerated electrons in the shock front of the jets. The forward\\nshock emission is from the heated electrons in the swept-up ambient\\nmedium, whereas the reverse shock emission is from the electrons of\\nthe jet itself when a shock moves back through the ejecta. The same\\nprocesses should also happen in the case of microquasars, with only\\nthe Lorentz factor much lower. In Wang et al. (2003), they tested\\nthese two possibilities and proved that the forward shock emission\\nwould decay too slowly to fit for the observed decay index\\n$-3.7\\\\pm0.7$ of the eastern jet, because of the continuously heating\\neffect. However, since only operating once, the reverse shock\\nemission could decay rather fast as the electrons cooled\\nadiabatically and this model indeed performed quite well in\\ndescribing the data. In the case of the western jet, the energy flux\\ndecayed even more rapidly (decay index $\\\\sim-5.1\\\\pm0.1$, see Fig. 5)\\nand as a result, we take the reverse shock mechanism in our work.\\n\\nAssuming the distribution of the electrons obeys a power-law form,\\n$n({\\\\gamma_{\\\\rm{e}}})d\\\\gamma_{\\\\rm{e}}=K\\\\gamma_{\\\\rm{e}}^{-p}d\\\\gamma_{\\\\rm{e}}$,\\nfor $\\\\gamma_{\\\\textrm{\\\\tiny m}}<\\\\gamma_{e}<\\\\gamma_{\\\\textrm{\\\\tiny\\nM}}$, the volume emissivity at frequency $\\\\nu\\'$ in the comoving\\nframe is given by (Rybicki \\\\& Lightman 1979)\\n\\\\begin{equation}\\nj_{\\\\nu\\'}=\\\\frac{\\\\sqrt{3}q^{3}}{2m_{\\\\rm{e}}c^{2}}(\\\\frac{4{\\\\pi}m_{\\\\rm{e}}c\\\\nu\\'}{3q})^{\\\\frac{(1-p)}{2}}B_{\\\\perp}^{\\\\frac{(p+1)}{2}}KF_{1}(\\\\nu,\\\\nu\\'_{\\\\rm{\\\\tiny\\nm}},\\\\nu\\'_{\\\\rm{\\\\tiny M}}),\\n\\\\end{equation}\\nwhere\\n\\\\begin{equation}\\nF_{1}(\\\\nu,\\\\nu\\'_{m},\\\\nu\\'_{M})=\\\\int_{\\\\nu\\'/\\\\nu\\'_{M}}^{\\\\nu\\'/\\\\nu\\'_{m}}F(x)x^{(p-3)/2}dx,\\n\\\\end{equation}\\nwith $F(x) = x\\\\int_x^{+\\\\infty}K_{5/3}(t)dt$ and $K_{5/3}(t)$ is the\\nBessel function. The physical quantities in these equations include\\n$q$ and $m_{\\\\rm{e}}$, the charge and mass of the electron,\\n$B_{\\\\perp}$, the magnetic field strength perpendicular to the\\nelectron velocity, and $\\\\nu\\'_{m}$ and $\\\\nu\\'_{M}$, the characteristic\\nfrequencies for electrons with $\\\\gamma_{m}$ and $\\\\gamma_{M}$.\\n\\nAssuming the reverse shock heats the ejecta at time $t_{0}$ at the\\nradius $R_{0}$ (with the assumptions of no synchrotron cooling,\\nconservation of the total number of electrons and the magnetic field\\nbeing frozen into the plasma), the physical quantities in the\\nadiabatically expanding ejecta with radius $R$ evolve as (van der\\nLaan 1966)\\n\\\\begin{equation}\\n\\\\gamma_{m}=\\\\gamma_{m}(t_{0})\\\\frac{R_{0}}{R},\\n\\\\gamma_{M}=\\\\gamma_{M}(t_{0})\\\\frac{R_{0}}{R},\\n\\\\end{equation}\\n\\\\begin{equation}\\nK=K(t_{0})(\\\\frac{R}{R_{0}})^{-(2+p)}, B_{\\\\perp}=B_{\\\\perp}(t_{0})(\\\\frac{R}{R_{0}})^{-2},\\n\\\\end{equation}\\nwhere the initial values of these quantities are free parameters to\\nbe fitted in the calculation.\\n\\nWith these assumptions, we can then calculate the predicted flux evolution of the jets.\\nThe comoving frequency $\\\\nu\\'$ relates to our observer frequency $\\\\nu$ by $\\\\nu=D\\\\nu\\'$,\\nwhere $D$ is the Doppler factor and we have $D_{\\\\rm{a}}=1/\\\\Gamma(1-\\\\beta\\\\cos\\\\theta)$\\nand $D_{\\\\rm{r}}=1/\\\\Gamma(1+\\\\beta\\\\cos\\\\theta)$ for the approaching and receding jets\\nrespectively. Considering the geometry of the emission region, the observed X-ray flux\\nin 0.3-8 keV band could be estimated by\\n\\\\begin{equation}\\nF(\\\\rm{0.3-8\\nkeV})=\\\\int_{\\\\nu_{1}}^{\\\\nu_{2}}[\\\\frac{\\\\theta_{j}^{2}}{4}(\\\\frac{R}{d}){\\\\Delta}RD^{3}j_{\\\\nu\\'}]d\\\\nu,\\n\\\\end{equation}\\nwhere ${\\\\Delta}R$ is the width of the shock region and is assumed to\\nbe ${\\\\Delta}R=R/10$, after Wang et al. (2003) in the calculation.\\n\\nTo reduce the number of free parameters, we set $\\\\gamma_{m}=100$ in\\nour calculation because the results are quite insensitive to this\\nvalue. According to our kinematic model in section 4.1, we choose\\nthe time that the reverse shock takes place to be the time that the\\nLorentz factor reduced to $1/\\\\sqrt{2}$ of its original value, which\\nis called deceleration timescale $t_{\\\\rm{dec}}$ in the GRB external\\nshock model, which is supposed to be the strongest point of the\\nexternal shock (Private communication with X. Y. Wang). Then we fit\\nthe data to find out the initial values of $K$ and $B_{\\\\perp}$.\\n\\nJust like the fitting to the kinematics of the jets, we could not\\ndecide the best fitting result only using the flux data since we\\ncould always find one group of parameters that fit the flux data\\napproximately well for each parameter $r$. Thus, we combine the\\nkinematic and light curve fitting together to find some more useful\\nhints.\\n\\nWe know that the energy and the number density of the gas in the\\npre-shock and post-shock regions are connected by the jump\\nconditions $n\\'=\\\\zeta(\\\\Gamma)n$ and $e\\'=\\\\eta(\\\\Gamma)nm_{p}c^{2}$,\\nwhere $\\\\zeta(\\\\Gamma)$ and $\\\\eta(\\\\Gamma)$ are coefficients related to\\nthe jet velocity (Wang et al. 2003 ). Therefore if we assume the\\nshocked electrons and the magnetic field acquire constant fractions\\n($\\\\epsilon_{\\\\rm{e}}$ and $\\\\epsilon_{B}$) of the total shock energy,\\nwe have\\n\\\\begin{equation}\\n\\\\gamma_{m}=\\\\epsilon_{e}\\\\frac{p-2}{p-1}\\\\frac{m_{p}}{m_{e}}(\\\\Gamma-1),\\nK=(p-1)n\\'\\\\gamma_{m}^{p-1},\\n\\\\end{equation}\\nand\\n\\\\begin{equation}\\nB_{\\\\perp}=\\\\sqrt{8\\\\pi\\\\epsilon_{B}e\\'}\\n\\\\end{equation}\\nfor p$>$2. Since we have assumed that $p$ and $\\\\Gamma_{0}$ (so that\\n$1/\\\\sqrt{2} \\\\Gamma_{0}$) are equal for the two jets, if we further\\nassume that factor $\\\\epsilon_{e}$ of the eastern and the western\\njets is also the same, we may infer that $K\\\\propto{e\\'}\\\\propto{n}$\\nfor the two jets. We therefore search for the combination of\\nparameters that could satisfy the kinematic and light curve fitting,\\nas well as the relationship\\n$K_{\\\\rm{e}}/K_{\\\\rm{w}}{\\\\sim}n_{\\\\rm{e}}/n_{\\\\rm{w}}$.\\n\\nTo search for the best parameters fitting the data, we follow the\\nfollowing procedure. With numerical calculations, for the 19 data\\npoints (including 10 kinematic data and 9 light curve data) we build\\na large 8-dimensional database for the eight parameters to be\\nestimated, with one constraining relationship,\\n$K_{\\\\rm{e}}/K_{\\\\rm{w}}{\\\\sim}n_{\\\\rm{e}}/n_{\\\\rm{w}}$. Intuitively it\\nlooks very difficult to determine so many parameters from so few\\ndata points. However, one approach we take is that we divide the\\nfittings into two stages: we first fit the kinematic data regardless\\nof the lightcurve information and get a series of $(r, n)$ all of\\nwhich describe the data almost equally well. Then, for each set of\\n$(r, n)$, we fit the lightcurve and calculate the joint $\\\\chi^{2}$\\nvalue to choose the group of parameters yielding the least\\n$\\\\chi^{2}$ value. The advantage of this approach is that, since\\n$(r, n)$ is fixed every time in the fitting of the lightcurve, we\\nconsider the kinematic fittings to be independent of the lightcurve\\nfittings in calculating $\\\\chi^{2}$. At each search step, the total\\n$\\\\chi^{2}$ is calculated corresponding to the 19 data points.\\n\\nA set of parameters that yields the minimum total $\\\\chi^{2}$ is\\ntaken as our best fitting parameters. The resulting total $\\\\chi^{2}$\\nis 7.05 and the errors are estimated by searching for the range for\\none parameter that can change the $\\\\chi^{2}$ value by a given delta\\nwhile keeping all the other parameters fixed (Press et al. 1992,\\n``Constant Chi-Squared Boundaries as Confidence Limits\"). The result\\ncorresponding to the lightcurve fitting is shown in Fig.5 and the\\ncorresponding kinematic fitting is shown in panel (c) in Fig.4. The\\nbest fitting parameters are listed in Table 4. From the parameters,\\nwe conclude that the boundary of the cavity lies at $r\\\\sim$12 arcsec\\nto the east and $\\\\sim$17 arcsec to the west of the central source.\\nThe corresponding number density of the ISM outside this boundary is\\n$\\\\sim$0.0034 cm$^{-3}$ and $\\\\sim$0.12 cm$^{-3}$, respectively. These\\nvalues are both lower than the canonical ISM value of $\\\\sim$1\\ncm$^{-3}$, although the value in the western region is much higher\\nthan in the eastern region. The asymmetry of the density on the both\\nsides probably involves the generation history of the cavity, which\\nshould be explored with further studies. The electron energy\\nfraction relationship is satisfied as\\n$K_{\\\\rm{e}}/K_{\\\\rm{w}}{\\\\sim}n_{\\\\rm{e}}/n_{\\\\rm{w}}\\\\sim0.03$. However,\\nwe should mention here that the other relation concerning the\\nmagnetic field strength (if $\\\\epsilon_{\\\\tiny{B}}$ are equal on the\\ntwo sides, then\\n$B_{\\\\rm{e}}/B_{\\\\rm{w}}{\\\\propto}\\\\sqrt{e\\'_{\\\\rm{e}}/e\\'_{\\\\rm{w}}}{\\\\propto}\\\\sqrt{n_{\\\\rm{e}}/n_{\\\\rm{w}}}$)\\ncould not be satisfied simultaneously by these parameters. Although\\nthe cavity radius and the number density are allowed to vary\\nsignificantly, the best fitted magnetic field strength remains quite\\nstable ($\\\\sim$0.35-0.55 mG). One possible interpretation for this is\\nthat the equipartition parameter varies as the physical conditions\\nof the jet varies or equipartition assumptions do not hold here for\\nthe magnetic fields since this is not a steady system; an\\nalternative explanation may involve the {\\\\it in situ} generation (or\\namplification) of the magnetic field (e.g., originated from external\\nISM instead of from the jet itself).\\n\\nIn the fitting, the assumed initial Lorentz factor is\\n$\\\\Gamma_{0}=3$, indicating an initial velocity of $v\\\\sim0.943c$. The\\nfixed spectral index, $p=2.2$, is consistent with the value obtained\\nby Xue et al. (2008) in their broadband spectral analysis\\n($p\\\\sim2.20-2.31$). The fitted magnetic field strengths is lower\\nthan the value given by Xue et al. (2008) ($B\\\\sim1-32$ mG). However,\\nthey claimed a large uncertainty in their fittings. We look forward\\nto further analysis to explore this more clearly and take our\\nfitting as a reasonable one at this stage.\\n\\n\\\\placetable{table4}\\n\\n\\\\begin{deluxetable}{rrrrrr}\\n\\\\tabletypesize{\\\\footnotesize} \\\\tablecolumns{6} \\\\tablewidth{0pc}\\n\\\\tablecaption{Model Fitting Results of the Eastern and Western\\nJet\\\\label{table4}} \\\\tablehead{\\\\colhead{} & \\\\colhead{Eastern jet}&\\n\\\\colhead{Western jet}& \\\\colhead{$n_{\\\\rm{e}}/n_{\\\\rm{w}}$} &\\n\\\\colhead{$K_{\\\\rm{e}}/K_{\\\\rm{w}}$} &\\\\colhead{Comments}\\n }\\n\\n \\\\startdata\\n$r$ (arcsec) &$12\\\\pm0.3$ &$17\\\\pm0.1$ & & &Cavity radius \\\\\\\\\\n$n$ (cm$^{-3}$) &$(3.4\\\\pm0.3)\\\\times10^{-3}$ &$0.12\\\\pm0.01$ & & &ISM density outside the cavity \\\\\\\\\\n$\\\\theta$ (\\\\textordmasculine) &68 &68 & & &Line of sight angle \\\\\\\\\\n$r_{0}$ (arcsec) &15.0 &17.9 &0.03 &0.03 &Reverse shock hitting place\\\\tablenotemark{a} \\\\\\\\\\n$t_{0}$ (days) &343 &842 & & &Reverse shock hitting time\\\\tablenotemark{a} \\\\\\\\\\n$B_{\\\\perp}(t_{0})$ (mG) &$0.51\\\\pm0.03$ &$0.38\\\\pm0.003$ & & &Initial value at $t_{0}$ \\\\\\\\\\n$K(t_{0})$ (cm$^{-3})$ &$(9.0\\\\pm1)\\\\times10^{-3}$ &$0.32\\\\pm0.03$ & & &Initial value at $t_{0}$\\\\\\\\\\n$\\\\chi^{2}$ for fitting &kinematics: 1.46 &kinematics: 1.55 & & &total $\\\\chi^{2}$=7.05 reaches the minimum \\\\\\\\\\n &light curve: 1.68 &light curve: 1.68 & & & \\\\\\\\\\n \\\\enddata \\\\tablenotetext{a}{The place and time\\nthat the Lorentz factor reduced to $1/\\\\sqrt{2}$ of its original\\nvalue, according to the kinematic model.}\\n\\n\\\\end{deluxetable}\\n\\n\\\\placefigure{fig5}\\n\\\\begin{figure}\\n\\\\includegraphics[width=12cm]{f5.eps}\\n\\\\caption{Model fittings to the X-ray light curves of the eastern and\\nwestern jets. A power-law plus Galactic absorption spectral model is\\nused to obtain the energy flux in the 0.3-8 keV band. The two solid\\nlines are the theoretical model fittings for the reverse shock\\nheated ejecta emission.} \\\\label{fig5}\\n\\\\end{figure}\\n\\n\\\\section{ANALYSIS OF JETS IN H1743-322}\\nH 1743-322 is an X-ray transient first discovered in 1977\\n(Kaluzienski \\\\& Holt 1977). It was then classified as a black hole\\ncandidate in 1984 based on its X-ray spectral characteristics (White\\n\\\\& Marshall 1984). New activity was found by INTEGRAL in 2003\\n(Revnivtsev et al. 2003), and a bright radio flare was observed by\\nVLA on 2003 April 8 (Rupen et al. 2003). $\\\\it Chandra$ X-ray and\\nATCA radio observations from 2003 November to 2004 June revealed the\\npresence of large-scale jets on both sides (Rupen et al. 2004;\\nCorbel et al. 2005). The source is then labeled as a ``microquasar\".\\n\\nWe take the data from the work of Corbel et al. (2005) and fit the\\nproper motion with the external shock model. Following their\\napproach, the ejection date is set to the time of the major radio\\nflare (2003 April 8). The distance to H 1743-322 is basically\\nunknown now. However, its location toward the Galactic bulge could\\npossibly imply a Galactic center location. Assuming a source\\ndistance of 8 kpc (distance to the Galactic center), the first radio\\ndetection of the jets gives out an intrinsic velocity of the\\nejection of $\\\\beta=v/c=0.79$ and an angle of\\n$\\\\theta=73\\\\textordmasculine$ for the axis of the jets (Corbel et al.\\n2005).\\n\\nHowever, the evolution of the jets shows that the velocity is not\\nconstant all the way through. Deceleration is required since the\\nlinear extrapolation of the proper motion data yields an ejection\\ndate earlier than the chosen zero point time, as shown in panel (a)\\nin Fig. 6. The linear extrapolation of the zero point and the first\\ndata point also gives out lines with steeper slope than the real\\ndata.\\n\\nAs a result, we also apply the external shock model to this source.\\nThe line of sight angle is set to be $\\\\theta=73\\\\textordmasculine$ in\\nall fittings. It is worth mentioning that the 73 degree angle is\\nonly valid if the jets have both been propagating outwards with the\\nsame speed and the same angle to the line of sight and the source is\\nassumed to be located at the Galactic center with a distance of 8\\nkpc. However, since there are no better constraints on the jet\\norientation, we simply take this value as a reasonable\\napproximation. We first test the model that assumes the source\\nlocated in a continual gas medium. In this case, the jets would\\ndecelerate gradually after ejection. The model fits the data quite\\nwell this time (panel (b) in Fig.6, with $\\\\chi^{2}$=1.03 for the\\napproaching jet and $\\\\chi^{2}$=0.98 for the receding jet, with\\ndegree of freedom=2 for each case), indicating that a cavity is not\\nrequired in this source. However, we also notice that the best\\nfitting density of the environment ISM is $n\\\\sim3\\\\times10^{-4}$\\ncm$^{-3}$, much lower than the canonical Galactic ISM value. We also\\napply the cavity model to the fitting, which describes the data\\nequally well (panel (c) in Fig. 6, with $\\\\chi^{2}$=0.95 for the\\napproaching and $\\\\chi^{2}$=0.97 for the receding jet, with degree of\\nfreedom=2 for each case), with a cavity region with radius of 3\\narcsec on both sides and the gas density of $n\\\\sim3\\\\times10^{-3}$\\ncm$^{-3}$. This value is one magnitude higher than the previous\\nattempt, but still quite low. Due to the limited data, we cannot\\ntest if the environment outside the central source is symmetric or\\nnot. The flux is not fitted for this source because of the limited\\nnumber of X-ray data points.\\n\\n\\n\\\\placefigure{fig6}\\n\\\\begin{figure}\\n\\\\includegraphics[width=9cm,height=18cm]{f6.eps}\\n\\\\caption{Model fittings to the proper motion of the radio and X-ray\\njets of H 1743-322. Panel (a) shows the constant velocity fitting\\nand Panel (b) and (c) are deceleration model fittings. Panel (a):\\nDotted lines: extrapolation of the zero point time and the first\\nradio detection. Solid lines: linear fittings to the data set with\\nconstant velocity. Panel (b): Deceleration in constant density\\nmedium. Results: $\\\\Gamma_{0}=1.65, \\\\theta=73\\\\textordmasculine,\\nE_{0}=1\\\\times10^{44}$ erg, $n\\\\sim3\\\\times10^{-4}$ cm$^{-3}$. Panel\\n(c): Deceleration in medium outside a cavity region. Results:\\n$\\\\Gamma_{0}=1.65, \\\\theta=73\\\\textordmasculine, E_{0}=1\\\\times10^{44}$\\nerg, $r_{\\\\rm{e}}=r_{\\\\rm{w}}=3$ arcsec, $n\\\\sim3\\\\times10^{-3}$\\ncm$^{-3}$. } \\\\label{fig6}\\n\\\\end{figure}\\n\\n\\\\section{GENERAL PICTURE OF MICROQUASAR ENVIRONMENT}\\nThe above analyses of XTE J1550-564 and H 1743-322 led us to the\\nconclusion that in microquasars the interactions between the ejecta\\nand the environmental gas play major roles in the jet evolution. We\\ncould further argue that the low density of the environment is a\\nnecessary requirement for the jet to develop to a long distance.\\n\\nHeinz (2002) derived the scale relations for the jets from accreting\\nblack holes, using a simple analytic model. He adopted the jet-ISM\\ninteraction scenario to estimate the slow-down distance of the\\nejecta:\\n\\\\begin{equation}\\nd_{\\\\rm{slow}}\\\\sim10^{16}\\\\rm{cm}(E_{44}/\\\\Gamma_{5}^{2}n_{x}\\\\theta_{5}^{2})^{1/3},\\n\\\\end{equation}\\nwhere $E_{\\\\rm{kin}}\\\\equiv10^{44}E_{44}$ erg is the kinetic energy,\\n$\\\\Gamma_{5}\\\\equiv\\\\Gamma/5$ is the Lorentz factor of the jet, $n_{x}$\\nis the external gas density in the unit of cm$^{-3}$ and\\n$\\\\theta=5\\\\textordmasculine\\\\theta_{5}$ is the opening angle of the\\njet. He applied this estimation to microquasars GRS 1915+105 and GRO\\nJ1655-40. In both cases, he found that the upper limit on the gas\\ndensity is roughly $10^{-3}$ cm$^{-3}$, given $d_{\\\\rm{slow}}$ of\\n~0.05pc, quite consistent with the ISM density found for XTE\\nJ1550-564 and H1743-322 in this work. For a larger $d_{\\\\rm{slow}}$,\\na lower $n_{x}$ should be required.\\n\\n\\\\placefigure{fig7}\\n\\\\begin{figure}\\n\\\\includegraphics[width=12cm]{f7.eps}\\n\\\\caption{Normalized proper motions of microquasars\\' approaching\\njets, obtained by dividing the actual jet length by the central\\ncompact object mass. For the mass and distance estimations, please\\nrefer to the text, see section 6. Jet kinematics data are taken from\\nRodriguez \\\\& Mirabel (1999), Gallo et al. (2004), Corbel et al.\\n(2005) and this paper respectively.} \\\\label{fig7}\\n\\\\end{figure}\\n\\nHeinz\\'s approach led to an interesting comparison between the\\nmicroquasar jets and the radio quasar jets. He claimed that the jets\\nlength in GRS 1915+105 ($l>$0.04 pc) would correspond to a jet\\nlength of 4 Mpc when scaled by $M$ (mass of the central black hole)\\nto AGN conditions (such as M87 or Cyg A) (2002). We could follow\\nthis way and infer that the jet in XTE J1550-564 ($l>$0.5 pc) will\\ncorrespond to a 50 Mpc long AGN jet, which has never been detected.\\nThis again confirms that the environment of microquasars should be\\ncomparatively vacuous, in a dynamical sense even (although not in\\nthe absolute sense) less dense than the AGN environment (the\\nintergalactic medium of densities between 10$^{-5}$ cm$^{-3}$ to\\n10$^{-2}$ cm$^{-3}$), when compared to the thrust of the jets in\\nmicroquasars and AGNs. When presented in unit of pc with the\\ninformation of source distance and scaled by the central black hole\\nmass, the proper motions of different microquasar jets can be\\nplotted in one figure (Fig. 7) (GRS 1915+105: 14$\\\\pm$4 $M_{\\\\odot}$\\n(Greiner et al. 2001), 12.5 kpc (Rodr\\\\\\'{\\\\i}guez et al. 1995); GX\\n339-4: 5.8$\\\\pm$0.5 $M_{\\\\odot}$ (Hynes et al. 2003), lower limit\\nestimation of distance of 4 kpc (Zdziarski et al. 1998); XTE\\nJ1550-564: 10.5$\\\\pm$1.0 $M_{\\\\odot}$ and 5.3 kpc (Orosz et al. 2002);\\nH 1743-322: since no good mass and distance observation up to date,\\nwe follow the assumption of 10 $M_{\\\\odot}$ (Miller et al. 2006) and\\ngalactic center origin of 8 kpc (Corbel et al. 2005)). It is\\ninteresting to notice from this figure that although the detailed\\nproperties of the binary systems (e.g., the compact objects and the\\ncompanion stars) differ a lot from source to source, the normalized\\njet proper motions are quite consistent. This is not surprising\\nsince the jet properties are set by the compact object (and its\\nimmediate neighborhood) and their evolutions are mostly influenced\\nby the surrounding environment. Although the companion star provides\\nthe material which is eventually launched into the jets, and thus\\naffects the mass transfer rate and the mass flux in the jets, it\\nnevertheless does not seem to play significant roles for the\\nstructure and evolution of the large scale jets and cavities\\nsurrounding the microquasar. Therefore the nature of accretion disk\\nphysics dominates over the nurture of the companion star, as far as\\nthe jets are concerned. Thus it leads us to the attempt to\\ngeneralize the microquasar jets in one consistent picture.\\n\\n\\nThis figure, together with other observational data concerning the\\nmotionless large scale jets (e.g., Cyg X-1, SS433), has led us to\\nthe suggestion that all microquasar jets can be classified into\\nroughly three groups: small scale moving jets, large scale moving\\njets and large scale jet relics. For the first type, the ``small\\njets\", only radio emissions are detected. The jets are always\\nrelatively close to the central source and dissipate very quickly.\\nExamples of this class include GRS 1915+105 (Rodr\\\\\\'{\\\\i}guez \\\\&\\nMirabel 1999; Miller-Jones et al. 2007), GRO J1655-40 (Hjellming \\\\&\\nRupen 1995), and Cyg X-3 (Mart\\\\\\'{\\\\i} et al. 2001). The typical\\nspatial scale is 0$\\\\sim$0.05 pc and the time scale is several tens\\nof days. In this class, no obvious deceleration is observed before\\nthe jets become too faint. For the second type, the ``large jets\",\\nboth X-ray and radio detections are obtained, at a place far from\\nthe central source several years after the outburst. Examples are\\nXTE J1550-564, H1743-322, and GX 339-4 (Gallo et al. 2004). The\\ntypical jet traveling distance for this type is 0.2$\\\\sim$0.5 pc from\\nthe central engine. Deceleration is clearly observed in this type of\\nsources. The last type, the ``large relics\", is a kind of diffuse\\nstructures observed in radio, optical and X-ray band, often ring or\\nround nebula shaped that are not moving at all. In this class, some well studied sources, Cygnus X-1 (Gallo et al. 2005), SS433 (Dubner el\\nal. 1998), Circinus X-1 (Stewart et al. 1993, Tudose et al. 2006)\\nand GRS 1915+105 (Kaiser et al. 2004) are included. The typical\\nscale for this kind is 1$\\\\sim$30 pc, an order of magnitude larger\\nthan the second type. The estimated lifetime often exceeds one\\nmillion years, indicating that they are related to previous\\noutbursts.\\n\\nFrom these properties, it is reasonable to further suggest a\\nconsistent picture involving all the sources together. We make a\\nconjecture that extreme low density regions, or namely, large scale\\ncavities, exist in all microquasar systems. The ``small jets\"\\nobserved right after the ejection are just traveling through these\\ncavities. Since there are few or none interactions between the jets\\nand the surrounding gas in this region, the jets travel without\\nobvious deceleration. The emission mechanism is synchrotron\\nradiation by particles accelerated in the initial outburst. The\\nemissions of jets decay very quickly and are not detectable after\\nseveral tens of days. In some cases (e.g. XTE J1550-564), the cavity\\nhas a dense (compared to the cavity) boundary at some radius and the\\ninteractions between the jets and the boundary gas heat the\\nparticles again and thus make the jets detectable again. Those are\\nthe ``large jets\". The emission mechanism then is synchrotron\\nradiation by the re-heated particles in the external shocks. Then,\\nafter these interactions, the jets lost most of their kinematic\\nenergy into the ISM gradually, causing the latter to expand to large\\nscale structures, the ``large relics\", in a comparatively long time\\n(thousands to several millions of years) and create the observed\\nnebula-like jet-inflated bubbles.\\n\\nDifferent systems are allowed to fall into more than one of the\\nthree postulated groups. For example, Cygnus X-1 has small-scale\\nejecta (Fender et al., 2006) and also has a large-scale relic (Gallo\\net al., 2005). Also XTE J1550-564 has small-scale ejecta\\n(Hannikainen et al., 2001) and also large-scale jets (Corbel et al.,\\n2002). As we proposed in the above paragraph, the three\\nobservational groups are perhaps just three stages in a complete\\nejection evolution process: the ``small jets\" observed in the\\noutburst events will travel in dark and manifest themselves as the\\n``large jets\" when they hit the boundary of the cavity and\\neventually develop into the ``large relics\" gradually by the\\ncontinuous interactions and energy dissipation. If this conjecture\\nholds, then the three groups may not be actually ``three\" but just\\nthree phenomena in ``one\" system. The three groups identified here\\nare probably just observational manifestations of one generic\\nmechanism, and different sources can belong to multiple groups.\\n\\nIf this general model of microquasars is true, properties of\\ndifferent jet systems could be dealt with separately in one\\nconsistent scheme. One implication is that the electrons from the\\n``large jet\" and the ``small jets\" belong to different groups of\\nelectrons, from the ejecta itself and the ISM respectively, which\\nmeans we could not simply use the properties of electron\\ndistributions in the ``large jet\" blobs to determine the emission\\nproperties of the central source in the ejection (Xue et al. 2008).\\n\\nOne important remaining question would be why there are such vacuous\\nregions and how to generate them. There are several possibilities,\\ninvolving previous outbursts, jets or winds activities. Before we go\\nfurther into these possibilities, we should first distinguish one\\nclass from the others. We have used the term ``cavity\" all through\\nour discussion, but actually there are two geometric possibilities\\nfor a cavity. One is a ``cavity\", the other is a ``tunnel\". Instead\\nof a spherical cavity, it is possible that there is only a vacuum\\nconical path outside the central engine. It may be created by\\nprevious jet ejection events and got fully developed through a\\nseries of ejections. This could explain the collimation of the jets\\nnaturally, but it requires almost continuous jet ejections (contrary\\nto the episodic jet ejections discussed here) to prevent the\\nsurrounding gas to fall back and fill up the thin path between\\nejections.\\n\\nThis assumption is of great interest because it provides a possible\\nconnection between the large-scale structures and the persistent,\\nlow-power, steady jets reported in several important observations\\n(etc. Cyg X-1 (Stirling et al. 2001) and GRS 1915+105 (Dhawan et al.\\n2000)). Kaiser and Alexander (1997, hereafter KA97) has developed a\\nmodel for radio galaxies in which continuous and collimated jet may\\nclear its way out and create a hot spot at the end of its path, and\\nthe hot electrons escaped from the shocks would form a ``cocoon\"\\noutside the central compact object. If this is also the case for\\nGalactic accretion systems, as postulated for Cygnus X-1 (Gallo et\\nal., 2005), Circinus X-1 (Tudose et al., 2006), and GRS 1915+105\\n(Kaiser et al., 2004), then the vacuous regions (tunnel and cocoon)\\nand the ``large relics\" are perhaps both the results of the\\ncontinuous jets traveling in dark. The two Galactic center sources\\n1E1740-294 and GRS 1958-258 may also belong to this case. In this\\nframe of assumptions, the episodic outbursts are not included here:\\nthe outbursts will increase the instantaneous mass flux down the\\njet, however since low-mass X-ray binaries spend the majority of\\ntheir time in a low-luminosity quiescent state, the outbursts will\\nhave little effect on the time-averaged jet luminosity, and thus on\\nthe long-term evolution of the relics. However, we may infer that if\\nthere are dark continuous jets and dark relics in a system like XTE\\nJ1550-564, a strong episodic outburst would just hit and brighten\\nthe boundary of the relic and may provide a bridge between the\\nsource and the relic. If there are multiple outbursts, we will\\nexpect repeated ``large jets\" in the same direction with larger and\\nlarger lengths. Future observations would then be able to testify\\nthis possibility.\\n\\n\\n\\n\\\\placetable{table5}\\n\\n\\\\begin{deluxetable}{rrrrrrrr}\\n\\\\tabletypesize{\\\\footnotesize} \\\\tablecolumns{8} \\\\tablewidth{0pc}\\n\\\\tablecaption{Wind properties of microquasars\\\\label{table5}}\\n\\\\tablehead{\\\\colhead{Source Name} & \\\\colhead{Equip.}& \\\\colhead{M\\n($M_{\\\\odot}$)}& \\\\colhead{$r_{\\\\rm g}$ (km)\\\\tablenotemark{1}} &\\n\\\\colhead{Velocity (km/s)} &\\\\colhead{Line width (km/s)}\\n&\\\\colhead{$R_{\\\\rm{\\\\rm eje}}/r_{\\\\rm g}$} &\\\\colhead{$V_{\\\\rm{esc}}$\\n(km/s)\\\\tablenotemark{2}} }\\n\\n \\\\startdata\\nGRO J1655-40 &$\\\\it Chandra$\\\\tablenotemark{3} &7 &10.5 &300-1000 &300-500 &$10^{4.7}$ &1900 \\\\\\\\\\n & & & & & &$10^{5.7}$ &600\\\\\\\\\\n &XMM-Newton\\\\tablenotemark{4} & & &2600-4500 & &$5\\\\times10^{3}$ &6000\\\\\\\\\\n & & & & & &$2\\\\times10^{4}$ &3000\\\\\\\\\\nH 1743-322 &$\\\\it Chandra$ \\\\& RXTE\\\\tablenotemark{5} &10 &15 &$700\\\\pm200$ &$1800\\\\pm400$ &$10^{4}$ &4240\\\\\\\\\\nGRS 1915+105 &ASCA\\\\tablenotemark{6} &$14\\\\pm4$ &21 &1000 & &$10^{5}$ &1340\\\\\\\\\\n & Chandra\\\\tablenotemark{7} & & &$1100^{+360}_{-300}$ &$980^{+450}_{-420}$ &$3\\\\times10^{5}$ &770\\\\\\\\\\n \\\\enddata\\n\\\\tablecomments{\\\\textbf{1}. $r_{\\\\rm g}=GM_{\\\\rm BH}/c^{2}; \\\\textbf{2}.\\nV_{\\\\rm{esc}}(r)=\\\\sqrt{2GM_{\\\\rm BH}/r}$; \\\\textbf{3}. Netzer, 2006;\\n\\\\textbf{4}. Sala et al. 2006; \\\\textbf{5}. Miller et al. 2006;\\n\\\\textbf{6}. Kotani et al. 2000; \\\\textbf{7}. Neilsen \\\\& Lee 2009;}\\n\\n\\\\end{deluxetable}\\n\\nApart from this case, several other possibilities may take place.\\nOne possible way to create the observed cavities is through recent\\nsupernovae outbursts that produced the central black holes. However,\\nonly HMXBs should be close to their parent supernova remnants (being\\nyoung); accumulated velocity dispersion (scattering from spiral arms\\nor giant molecular clouds over time) will carry LMXBs far from their\\nnatal supernova remnant in a few Galactic orbits, e.g. for GRO\\nJ1655-40 (Israelian et al. 1999). Furthermore, some sources such as\\nCygnus X-1 most likely never had supernovae, because of their low\\npeculiar velocity (Mirabel \\\\& Rodr\\\\\\'{\\\\i}gues 2003). In the case of\\nrecent supernovae ($<10^{5}$ years) and low kick-out velocity for\\nthe black hole, SNRs surrounding them should have been detected, and\\nfor much older supernovae and very low kick-out velocity for the\\nblack hole, the microquasars may still resides in the SNRs but\\nregular interstellar medium should have filled those very old SNRs\\nnow.\\n\\nWinds from progenitors of the central compact objects at their last\\nstages may also be an interpretation. Cavities in hydrogen maps have\\nbeen detected around neutron stars and were supposed to be driven by\\nwind from the progenitors of the stars (Gaensler et al. 2005).\\nHowever, the lifetime of such bubbles were estimated to be of order\\nof $\\\\sim$1 Myrs. For a region still as vacuous as we have estimated\\nin our studies, the compact object is expected to be much younger\\nthan that. Winds of the companion star in the binary are also a\\npossible candidate. Wind-blown bubbles and shells are observed\\naround evolved massive stars, with typical radii of $\\\\sim$2-10 pc\\nfor Wolf-Rayet stars (Gruendl et al. 2000) and $\\\\sim$0.1-2.3 pc for\\nluminous blue supergiants (Smith et al. 2007). However, the\\nestimated density at the bubble shells is of order of $\\\\sim$100\\ncm$^{-3}$, simply too high for our case, and among all the well\\nestablished microquasar systems, only the companion star in Cyg X-1\\nis O type (O9.7Iab) (Remillard \\\\& McClintock 2006), whereas most of\\nthe other systems contain only M, K or G type companion stars, which\\nare not powerful enough to generate such large scale bubbles.\\n\\nA plausible possibility involves the accretion disk winds. In this\\nscenario, it is the disk winds with mild or non-relativistic\\nvelocities that have pushed away the surrounding ISM gas and created\\nthe low density regions surrounding the central source. The wind\\nshould go as shells that travel in a ballistic way while interacting\\nwith the ISM cold gas. Indeed, in several microquasars, fast ionized\\nwinds have already been observed (Miller et al. 2006; Kotani et al.\\n2000; Netzer, 2006; Sala et al. 2006; Fuchs et al. 2006). Strong\\nabsorption metal lines are detected with obvious blueshift. The\\nspeed of the outflow could be calculated from the blueshift of these\\nlines. The ejection place could also be estimated using the measured\\nionization parameters. We list some of the results in Table 5,\\nincluding the calculated escape velocity at the inferred ejection\\nradius ($r_{\\\\rm g}=GM_{\\\\rm BH}/c^{2}$ and\\n$v_{\\\\rm{esc}}(r)=\\\\sqrt{2GM_{\\\\rm BH}/r}=\\\\sqrt{2r_{\\\\rm g}c^{2}/r}$).\\nAlso, in another interesting work, Fuchs et al. (2006) showed that\\nthere are indeed strong subrelativistic winds coming out of the SS\\n433 system, very much alike the winds from a WR star or from a thick\\ntorus or envelope outside the accretion disk and the central object.\\nThe estimated mass lost rate is $4.7-7.3\\\\times10^{-5} M_{\\\\odot}$\\nyr$^{-1}$ for discontinuous winds and 3 times higher for continuous\\nwinds, much higher than the observed jet mass loss of $\\\\sim$10$^{-7}\\nM_{\\\\odot}$ yr$^{-1}$ in this system, and a double-cone structure may\\nbe formed by these winds. These inferences are also supported by\\nBlundell et al. (2001), where the equatorial radio emission seen in\\nSS433 was taken as evidence for a disc wind. These observations\\nsupport the idea of co-existence of jets and winds in the\\nmicroquasars systems. We also notice that the wind velocity in\\nH1743-322 is lower than those in GRS 1915 +105 and GRO J1655-40,\\nsuggesting larger cavities are formed for the latter two sources\\nthan for the former one. It is consistent with the fact that no\\ndecelerating jets have been observed in these two sources up to now.\\n\\nHowever, whether the winds are powerful enough to create such large\\ncavities in all cases for all sources is unclear at this stage. The\\nterminal places of the wind shells (which determine the size of the\\ncavity) are determined by the wind energy and geometry,\\nspecifically, the wind velocity at the ejection place and the\\nopening angle, and the interaction conditions between winds and the\\ngas. These parameters are still very uncertain nowadays because of\\nthe lack of enough studies and the densities of the winds are only\\nestimated at the foot of the ejection place. We would roughly\\nestimate that, in order for the wind to move to large radii far from\\nthe black hole, the wind velocity should be quite close to the\\nescape velocity at the ejection radius. From table 5, we can see\\nthat most of the observed wind velocities are comparable to,\\nalthough not as large as, the local escape velocity, with the\\nexception of the recently discovered disk wind of about its escape\\nvelocity in GRS 1915+105 in its soft state, with mass loss rate\\nsufficient to suppress jet ejection (Neilsen \\\\& Lee 2009). Therefore\\nin the last case the accretion disk wind alone (because no jet is\\nexpected in the soft state) may play a significant role for forming\\na large scale cavity. However for other cases the winds alone may\\nnot be enough to power the cavities, due to insufficient velocities.\\n\\nTherefore some kinds of acceleration or velocity-maintaining\\nmechanisms may be required, in order for the winds to expand far\\nenough ($\\\\sim$0.1 pc to 10 pc). Magnetic fields may play an\\nimportant role here. It has been known that rotating wind-up\\nmagnetic fields can accelerate and launch jets (see Spruit 2008 and\\nreferences therein); therefore continuous high velocity winds can\\nset up the favorable condition for producing continuous outflows or\\njets with velocities around or even exceeding the escaping\\nvelocities of these systems. Once continuous high velocity outflows\\nor jets are produced, they should be able to inflate their\\nsurrounding interstellar medium to form bubbles, as we have\\ndiscussed earlier within the framework of the KA97 model.\\n\\nFinally, we comment that it seems counter intuitive that the boundary of the cavity lies further in the western\\nside, yet the ISM density is also higher in the west. It would be a problem if the cavity is produced by the\\nobserved large scale two-sided jets with equal power. Therefore this asymmetry may be used to argue against such\\na model. However, the asymmetric cavity may be naturally produced if the system has a non-negligible space\\nvelocity with respect to the local ISM along the eastern direction. In this case additional energy is injected\\ninto the ISM on the head-on side along the direction of motion of the system, in analogy to process producing\\nthe head-on bow-shock of young spin-down powered pulsars moving in ISM (e.g., Caraveo et al 2003). Therefore the\\ncavity on the approaching side should be emptier (with smaller density) than the opposite wind or jet, unless\\nthe system moves perpendicular to the wind or jet. The system itself is also catching up with the cavity on the\\napproaching side, placing itself closer to the boundary of the cavity on the approaching side. For example, a\\nspace velocity of 100 km/s with respect to the local ISM would displace the source by 0.1 pc in less than 1000\\nyears. In the absence of data for this system on its proper motion and the power of wind or continuous (dark)\\njets, we will not speculate further on what combination of parameters may eventually produce the observed\\nasymmetry of the cavity. This should be tested in the future. Heinz et al. (2008) have proposed that the\\nmicroquasar\\'s space velocity should be important and leave trails behind their moving path in the Galaxy. They\\nestimated the volume of radio plasma released by these microquasars and claimed that they should be observable\\nat low frequencies. Future observational confirmation of their prediction for XTE J1550-564 would provide\\nevidence for our conjecture.\\n\\n\\n\\\\section{CONCLUSIONS AND PERSPECTIVES}\\nTwo large-scale X-ray jets have been observed in XTE J1550-564. We\\nhave analyzed the $\\\\it Chandra$ X-ray data for these two jets and\\nfitted their kinematics and light curves with the external shock\\nmodel in the GRB afterglow model. In this model, the interactions\\nbetween the jet material and the surrounding ISM slow the jets down\\nand accelerate the jet particles to radiate the observed radio and\\nX-ray synchrotron radiations. Under such assumptions, the number\\ndensity of the ISM in the surrounding regions of the central black\\nhole is a key parameter. We found in the fitting that this number\\ndensity has to be extremely low, or the strong interactions would\\nblock the jet\\'s expansion. However on the other hand, the number\\ndensity at $\\\\sim$20 arcsec has to be comparatively high (but still\\nlower than the typical ISM) in order to allow the jet to be\\ndecelerated quickly, as the observational data indicated. Thus, a\\nmodel consisting of two different regions, a cavity and its gas\\nboundaries, is tested and shown to work well. The cavity is found to\\nbe large scale ($\\\\sim$0.4 pc in size) and asymmetric ($n_{\\\\rm\\ne}/n_{\\\\rm w}\\\\sim0.03$). The reason of the asymmetry of the\\nenvironment on the two sides is not clear from current observational\\ndata. The deceleration described in the model is quite obvious (from\\n$\\\\Gamma_{0}=3$ to $\\\\Gamma_{t}\\\\simeq1$ at $t\\\\sim1500$ days), thus it\\nis the first time that we observe the whole process of the\\ndeceleration of a pair of relativistic jets.\\n\\nThe similar analysis of H1743-322 also supports this jet-ISM\\ninteraction scenario. Large scale decelerating jets are also\\nobserved in this source and the interaction model describes the data\\nconsistently. Whether a cavity exists is not clear in this case;\\nnevertheless the density is also found to be very low, compared to\\nthe canonical Galactic value.\\n\\nWith these studies, a generic model of the environment of\\nmicroquasars is proposed. We suggest that microquasars are located\\nin large scale and very low density cavities. The cavity provides\\nthe space for the jets to go through freely and the interactions\\nbetween the jets and the material outside the cavity provide the\\ndeceleration mechanism of the jets. The cavity is likely created by\\ncontinuous high velocity outflows or jets, which are seeded by\\naccretion disk winds that have been observed in several microquasar\\nsystems producing strong absorption lines.\\n\\nMicroquasars are powerful probes of both the central engine and\\ntheir surrounding environment. More studies of the jets behaviors\\nmay give us information on the ISM gas properties, as well as the\\nejecta components. The link between jets and wind is a key issue in\\ncurrent studies of accreting systems. If the general scenario we\\nhave proposed here is further confirmed, we then need to understand\\nthe mechanism producing these outflows (winds and jets) and the\\nconnections between them. Detailed analysis of the geometry and\\ntiming properties of the ejecta in the future would be of great\\nsignificance; it will not only provide insights of the jet formation\\nprocess, but also offer another approach into black hole physics and\\naccretion flow dynamics.\\n\\n\\n\\\\acknowledgments\\n\\n\\\\textbf{Acknowledgments}\\n\\nWe are grateful to X.Y. Wang for many helps in this work. We also\\nthank Z.G. Dai and R. Soria for useful discussions. We appreciate\\nvery much the insightful comments and helpful suggestions by the\\nanonymous referee. SNZ acknowledges partial funding support by the\\nYangtze Endowment from the Ministry of Education at Tsinghua\\nUniversity, Directional Research Project of the Chinese Academy of\\nSciences under project No. KJCX2-YW-T03 and by the National Natural\\nScience Foundation of China under grant Nos. 10821061, 10733010,\\n10725313, and by 973 Program of China under grant 2009CB824800.\\n\\n\\n\\n'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "paper[9999][\"text\"]" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Filter: 0%| | 0/5489000 [00:00 27112)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "11235" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(book[2][\"text\"].split())" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "It was one of those rare days in London when the sun shone on clean streets and the air did not smell of rotten vegetables and horse dung. A night of heavy rain had washed the streets clean without, mercifully, overloading the sewer system, and the cobbles and brickwork of the city glistened proudly like a man showing off his freshly cut and oiled hair. Sherlock knew it wouldn't last for long, but for a while it made London into somewhere he thought he could live, one day.\n", "\n", "Sherlock and his tutor, Amyus Crowe, had left Farnham earlier that morning. Sherlock's brother Mycroft had invited them for lunch at his club – the Diogenes. His reason, which he explained in a letter that had arrived the day before, was that he wanted to talk about Sherlock's schooling. Having been removed from Deepdene School for Boys and placed in the care of the big American Amyus Crowe, it seemed to Sherlock that Mycroft was now wondering if he had done the right thing. Mr Crowe was a brilliant teacher, but only on certain subjects. Survival in the wilderness, tracking animals, fishing for carp and trout, identifying poisonous fungi, a little bit of recent political history and the logical analysis of evidence – these were all his strong points. Mathematics and Latin – not so much.\n", "\n", "Sherlock would much rather study the things that Amyus Crowe was teaching him, because he could see their value, but his brother had a strange regard for those areas of the syllabus for which Sherlock could see no earthly use. Every now and then he threatened to bring in another tutor to complement Crowe's lessons, and Sherlock had either to avoid the subject entirely or try to talk him out of it. 'If you want to make something of yourself,' he would say, 'then you need to learn dead languages, theology and the more obscure facts of history. There is no alternative, I'm afraid.' The fact that Sherlock had no idea what he wanted to make of himself cut no ice with his brother. 'You will go into the Civil Service, of course,' he would rumble. 'Either that or banking.'\n", "\n", "The hansom cab that Sherlock and Crowe had taken from Waterloo Station dropped them outside the Diogenes Club, which lurked behind an unremarkable door. Crowe, resplendent in his white suit and hat, flicked a coin up to the driver and strode across the pavement to the door, but as he did so a passing man in a suit and bowler hat jostled against him. Crowe turned to deliver a sharp rebuke, but the man unexpectedly pushed him in the chest. Crowe staggered backwards into two other men who were passing. Within moments, all four men were arguing.\n", "\n", "Unsure what to do, Sherlock stepped away from the cab. As he did so he heard movement behind him. Someone had come around the side of the cab and was looming at his shoulder. He turned his head, but liquid sprayed his eyes and nose. Gasping, he raised a hand to wipe his face clear, but his arm suddenly seemed to be moving in slow motion. His attention became fixated on his fingers and thumb. They looked like they weren't even a part of him: pink, fleshy things that moved of their own accord. The lines on his palm took on the appearance of rivers crossing a landscape, like a map seen at a distance.\n", "\n", "What was happening to him?\n", "\n", "He felt nauseous. His head felt like it had doubled in weight, and as he laboriously swung it around to look for Amyus Crowe he saw that the big American was staring at him in concern, but Crowe's face was swimming in and out of focus, and although his lips were moving Sherlock couldn't hear anything apart from what sounded like the tolling of a distant bell. The cab and the sky and the brickwork of the buildings were all bleeding together into a mishmash of colours that made him feel as if he was looking at the world through a stained-glass window. He needed to rest, to sit down and gather his wits, but when he took a step forward his feet tangled together and he stumbled. He fell, and it seemed to take an awfully long time before he hit the ground. A hand grabbed at his shoulder, but when he looked up, all he could see was a grotesquely distorted face looming over him. He struck out with his fists, again and again, flailing around in a world of jumbled shapes and colours. Someone was screaming, and he thought he recognized the voice. He thought it was his own voice, but it was a long, long way away.\n", "\n", "Then there was darkness, and the feeling that his arms were being tightly held. And then there was just the darkness.\n", "\n", "The realization that he was lying on a bed of straw in a brick-lined room came slowly. He didn't know at what point he understood where he was: there came a moment, as he was staring at the brickwork, that he realized that he _had_ understood some time ago, but the information just hadn't meant anything to him.\n", "\n", "He was in a brick room, and he was lying on straw. That was a starting point.\n", "\n", "And his name was Sherlock. Sherlock Holmes.\n", "\n", "The rest seeped back gradually, like the sea washing over the beach as the tide comes in. The Diogenes Club. The cab. The fight. The liquid that had been sprayed over his face.\n", "\n", "He checked his clothes, running his hands down his body. He was still wearing the same jacket, shirt and trousers that he had been wearing earlier. That, at least, was something to hold on to. They were stained with dust and dirt, but not ripped.\n", "\n", "The room was like the inside of a stable, but there was no smell of animals. The straw was clean and dry, and had been laid down on flagstones. The brickwork that formed the walls was whitewashed and dry too: no moss, no trickling water, and the air was chilly but not damp. At first he'd thought he was in some sort of outbuilding, but the evidence suggested otherwise. He was indoors – just not in a particularly well-appointed room.\n", "\n", "There was a window in one wall, but it was tall and thin, barely wide enough for him to get his arm through if he tried. Certainly not large enough for him to escape. Even his friend Matty wouldn't be able to get through that. The glass looked dirty, from where he lay.\n", "\n", "The wall opposite the window was interrupted by a door. It was heavy, and studded with big metal rivets like the heads of arrows that had been shot through from the other side. A small window in the centre of the door was barred, and it looked as if a wooden shutter had been closed across it from the other side.\n", "\n", "As Sherlock's mind began to speed up, he realized that there were no hinges on the door. Or, at least, there were no hinges on the inside of the door. The hinges must have been on the outside, which meant that the door opened outwards, not inwards. Sherlock didn't think that he'd ever been in a room where the door opened outwards.\n", "\n", "No, that wasn't right. He _had_ been in a room like that: the room in Bow Street Police Station where he and Amyus Crowe had spoken with his brother Mycroft a few months before. The door to that room had been designed so that people in the room could not pry the hinges apart and thus remove the door, or hide behind the door when it opened and attack whoever came in.\n", "\n", "He was in a cell.\n", "\n", "He sat up suddenly, shocked into complete wakefulness. He was in a cell! Surely he hadn't been arrested? Now that the blood was flowing more swiftly through his brain he remembered vague images of himself flailing around in the street, punching people who came too close – but Amyus Crowe would have protected him, wouldn't he? Protected him from arrest?\n", "\n", "Unless Crowe had been arrested too. The big American had been on the verge of a fight, after all.\n", "\n", "He checked his knuckles. They were scraped, and covered with dried blood.\n", "\n", "He tried to work out how long he had been unconscious. His throat and mouth were dry, but he wasn't particularly hungry. He couldn't have been out for more than a couple of hours. It was still the same day.\n", "\n", "He climbed unsteadily to his feet. His toes tingled with pins-and-needles as the circulation returned to them, and he shuffled from one foot to another to try to get the pain to subside. As soon as he could stand up straight he crossed to the window. It was above his head, but by reaching up and hooking his fingers over the sill and then pulling himself up, scrabbling with the toes of his boots to get purchase against the mortared ridges between the bricks, he could get his head up to a level where he could just about see out.\n", "\n", "Beyond the wall lay a manicured garden of lawns and bushes, and beyond them, just the other side of a wall, he could see the tops of hansom carriages going past. Lots of carriages. Pigeons were perched all along the top of the wall. It looked as if he was still in London.\n", "\n", "At least that was something.\n", "\n", "He dropped back down to the stone-flagged ground, brushing his hands against his trousers, and crossed to the door. There was no handle on the inside. He pushed experimentally at it. The door didn't budge. Presumably it was bolted on the other side.\n", "\n", "He threw his weight against it, but it didn't shift.\n", "\n", "He glanced back at the window. He may have been imprisoned but at least he wasn't in the countryside, or even in France. That had happened before. He was in London. Amyus Crowe would get him out.\n", "\n", "Assuming that Crowe wasn't in the next cell. The thought sent a cold shiver of fear through him. If he and Crowe were _both_ imprisoned here, and if Mycroft didn't know where they were, then there was nobody left to get any of them out. They might rot there forever.\n", "\n", "'Mister Crowe!' he called. 'Can you hear me? Are you there?'\n", "\n", "Nothing. No response.\n", "\n", "No, that wasn't entirely true. He _could_ hear something. Now that he was listening properly he could make out a faint cacophony of moans and cries coming from the other side of the door. It seemed to have got louder when he shouted. And he could hear banging as well: metal against metal in a regular, mindless rhythm. It was like listening to a musical recital in hell.\n", "\n", "The window in the door suddenly slid open. He jerked his head back, startled. A face stared in at him, framed in the wood: eyes wary and skin scabbed.\n", "\n", "'Back away,' a rough voice said. 'Back across to the other side of the room. This door ain't openin' till you do.'\n", "\n", "Sherlock shuffled away until his back was against the wall, feeling the straw piling up behind his feet as they scuffed across the floor.\n", "\n", "The window slid closed with a _thud_. Moments later he heard the solid _clunk_ of a large bolt being drawn, and then the door creaked open.\n", "\n", "Two men stood in the doorway. They both wore uniforms of blue canvas. Their hands were dirty and their faces unshaven. And they were both holding short wooden clubs.\n", "\n", "'Try anythin' an' you'll be measurin' your length on the floor, understand?' The speaker was the man on the left. He was slightly smaller than his companion, and his eyes were blue. 'Tell me you understand. Talk properly now.'\n", "\n", "'I understand,' Sherlock said, voice unsteady. 'Where am I?'\n", "\n", "The man turned to his companion. 'You 'ear that? He don't know where 'e is!' He turned back and smiled at Sherlock. His mouth was empty of all but three blackened teeth. 'You're in Bedlam, mate! Now come over 'ere, careful like. The Resident wants to take a look at you.'\n", "\n", "The two men backed away, leaving a path through the door. Sherlock walked gingerly forward, still trying to process what they had told him. Where was 'Bedlam'? Who was 'the Resident'?\n", "\n", "The men stepped back as he walked through the door. He noticed that they were holding their clubs ready, in case he attacked them. He was smaller than them, and unarmed, but they seemed to be scared of him. Or, at least, wary.\n", "\n", "Outside, he found himself in a long, wide gallery lined with doors on one side and narrow, barred windows on the other. The floor was wood, apparently polished by years of feet brushing against it. The ceiling of the gallery was curved, with iron rods every few feet making it seem as if Sherlock was standing inside the ribcage of some vast beast: an impression reinforced by the bloody glow emitted by a cave-like fireplace a few yards away. The fireplace was covered by a black metal cage which had been bolted to the wall.\n", "\n", "There were people in the gallery. Off to one side, four men were playing cards at a small table. Another man, in a black suit and top hat, was standing by one of the windows and looking out. The expression on his face was desperately sad. Other men – and they were all men, Sherlock noticed – were walking up and down the gallery, some slowly, with their hands reaching out to trail along the brickwork, and others rapidly, as if they had somewhere urgent to be.\n", "\n", "One man brushed past Sherlock with a curse. He walked ten feet further on, then stopped for a moment and turned around. He walked back, brushing past Sherlock again as if he had never seen him before, and strode off in the opposite direction. As Sherlock watched, he stopped again, turned around and walked back towards Sherlock once more.\n", "\n", "Now that he was out of his cell, he could hear the cacophony of voices more clearly. It sounded like several hundred people all having conversations and arguments with themselves, or singing, or wailing, all at once, and all in ignorance of the others.\n", "\n", "The voices came from behind the doors which lined one side of the gallery.\n", "\n", "Turning, he spotted a blackboard bolted to the wall beside his door. On it were chalked the words _Unknown boy – Acute mania_ , along with the date.\n", "\n", "The words were like spears of ice thrust into his heart.\n", "\n", "_Acute mania_.\n", "\n", "'This is a lunatic asylum,' he said, and he could hear his voice verging on breaking. 'This is where they send mad people.'\n", "\n", "'Like I said,' the attendant said: 'Bedlam. Or Bethlehem Hospital, to the gentry. Or the madhouse, to those of us who work 'ere.'\n", "\n", "Sherlock's keen eyes noticed that the bolt on his door was huge – probably a foot or more long. It was a design he'd seen elsewhere: a metal cylinder that slid back and forth inside a couple of metal brackets across into a narrow brass barrel on the doorframe to secure the door. The cylinder could then be rotated by its handle so that it caught behind one of the brackets on the door, stopping it from being slid back unless it was rotated again. Very simple, and quite foolproof. Even if Sherlock could have picked locks, which he couldn't, there was no obvious way out of the room. Accessing the bolt outside the door from inside would be almost impossible.\n", "\n", "If he was going to escape.\n", "\n", "'Now, 'ead down that way, to the end,' the attendant said, interrupting his chain of thought. 'That's where the Resident's office is. 'E likes to see all the new inmates. Very conscientious, is the Resident.' He pushed Sherlock's shoulder, backing away immediately in case Sherlock suddenly turned and grabbed him.\n", "\n", "Sherlock started to walk. A few doors were open, others were locked with the bolts pointing firmly downwards. Whoever ran this place liked an orderly system, the appearance of control. As he passed each locked door the noise of the occupant got suddenly louder, then quieter. He could hear words, sobs, screams, and in a couple of cases what sounded like music-hall songs.\n", "\n", "Perhaps the worst were the doors behind which he could hear no noise at all, but sense a malign presence, watching and waiting, like a spider in its web.\n", "\n", "A hand pushed Sherlock between his shoulder blades. He nearly went sprawling to the ground.\n", "\n", "'Move yourself,' the attendant called. 'We ain't got all day.'\n", "\n", "With the two attendants behind him, Sherlock walked the length of the gallery, past innumerable wooden doors and narrow windows and occasional caged fires which blasted heat all around them. At one of the cages an enterprising inmate was holding a long wooden stick in the flames, toasting something. For a few moments Sherlock thought it was a chunk of bread, but as he got closer he realized that it was a mouse, curled up and blackened.\n", "\n", "The man with the stick watched Sherlock and the attendants pass. 'I saw her again when they were all sleeping,' he said in a reasonable, calm voice. 'She walks in beauty, like the night.'\n", "\n", "'Good,' Sherlock replied. It was the only thing he could think of to say.\n", "\n", "One of the attendants snorted with laughter. 'Yeah, look out for ghosts, boy. Make sure you say your prayers and sleep nicely or you ain't going to like what you see.'\n", "\n", "The attendants pushed him to the end of the gallery, where a large grille, like a portcullis, separated it from the space beyond. It was a circular hall, with a domed roof. One of the attendants opened a door in the grille with a key selected from a bunch that hung from his belt and pushed it open. He went through, leaving his colleague behind Sherlock, and gestured to Sherlock to follow him. The two of them had obviously done this many times before. They had the whole process down pat.\n", "\n", "The domed hall into which they led Sherlock was opulent: painted white with gold-leaf ornamentation, and beautiful paintings hanging up on the walls. This area didn't have flagstones on the floor: it had black and white tiles. On Sherlock's left was a large door that, he guessed from the position of the windows along the gallery, led out into the grounds. On his right was a smaller, internal door. It wasn't locked or secured. Presumably it led into administrative areas: offices, examination rooms, kitchens, that sort of thing. And ahead of him, mirroring the floor-to-ceiling grille through which he had just passed, was another grille leading into another gallery. Vaguely, in the red firelight glow beyond, he thought he could see shapes moving. Women? A gallery for women, just as his was a gallery for men? More than likely.\n", "\n", "The toothless attendant pushed him towards the door to his right. 'Through there, then first door on your left. We'll be waiting outside. All the Resident has to do is shout, and we'll be straight in.' He suddenly lashed out with his club, catching Sherlock behind his left knee and sending a spike of sick agony up his thigh. Sherlock dropped to the floor, his leg suddenly unable to support his weight. His elbow hit the tiles, sending another wave of agony through him. He had to clench his jaw shut and swallow hard to stop himself from throwing up. 'And if we have cause to come in, you'll remember it for a very long time. Just bear that in mind.'\n", "\n", "He hauled Sherlock to his feet and pushed him towards the door. It swung open beneath the pressure of Sherlock's extended hand. Beyond it was a long corridor lined with doors. Attendants were walking along it, much as the inmates had walked along the gallery, and with the same mixture of purpose and purposelessness.\n", "\n", "Sherlock saw a door immediately on his left. A brass sign had been screwed to it. The words engraved on it said: _William Rhys Williams MD MRCS MRCPE – Resident Physician & Superintendent_.\n", "\n", "Sherlock glanced backwards, at the attendants. They were watching him carefully. He wondered if this was some kind of test: what would he do – knock politely, just stand there, or open the door and walk in unannounced?\n", "\n", "He knocked and waited.\n", "\n", "'Come in,' a voice called. He twisted the knob, pushed the door open and entered.\n", "\n", "The room inside was carpeted, panelled and curtained. It was, in a strange way, reminiscent of the Diogenes Club in its plushness and its quietness. A large desk was placed to one side, in front of a large window. Bookshelves to either side of the window were filled with leather-bound volumes. A man wearing a black suit, high-collared shirt and striped waistcoat sat behind the desk, writing with a quill pen in a ledger. He was bald, apart from a fringe of black hair running around the back of his head like a small curtain.\n", "\n", "The man glanced up at Sherlock. His gaze flickered all over Sherlock's face, hands, clothes, everything. He nodded, as if he had just confirmed a conclusion that he had reached before Sherlock had entered.\n", "\n", "'Stand in front of the desk,' he said. His voice was thin, whispery. 'My name is Doctor Williams. I am the Resident Physician at this institution. That means I have the final say when it comes to any decision regarding the inmates – of which you are one. I should warn you that if you make any move to come around the desk, or exhibit any violent or unwarranted behaviour, I will have no hesitation in calling on my attendants for assistance. Do you understand?'\n", "\n", "'I understand, sir,' Sherlock said, moving to the front of the desk. 'There has been a terrible mistake. I am—'\n", "\n", "'Be quiet. Answer questions when I ask them. Do not volunteer information, or I will have you removed back to your room.' Williams paused, and glanced down at the ledger on his desk. Sherlock noticed a small brass bell beside it. 'Do you know your name?'\n", "\n", "'Holmes, sir. Sherlock Scott Holmes.' He was about to say something else, but thought better of it.\n", "\n", "'Memory appears intact,' Williams murmured, making a note in the ledger. 'Locomotion and posture are reasonable for a boy of age –' he glanced up at Sherlock. 'How old are you?'\n", "\n", "'Fourteen, sir.'\n", "\n", "'– of age fourteen,' he continued. He leaned back in his chair, which creaked beneath his weight. 'I make it a habit formally to interview all new inmates. You have been sent here because you exhibited severe manic behaviour in a public place. The police restrained you, and a doctor present at the scene certified you insane. You will stay here until I – and I only – am convinced that you have recovered. Do you understand?'\n", "\n", "Sherlock's head was spinning. He was desperate to explain himself. 'I understand,' he said, 'but I am not insane!'\n", "\n", "'Nobody who is insane believes themselves to be insane,' Williams said. 'It is, I dare say, one of the defining characteristics of insanity.' He nodded. 'I have, as you might expect, made no small study of insanity. I was previously Assistant Doctor firstly at Derby County Asylum and then at the Bedfordshire, Hertfordshire and Huntingdonshire County Asylum. Eight years ago I was appointed Assistant Physician here under Doctor William Hood, whom I succeeded six years ago as Resident Physician. I tell you this so that you know there is no way you can pull the wool over my eyes. I can tell when someone is mad, and I can tell when they are sane.'\n", "\n", "'But, sir—' Sherlock started desperately.\n", "\n", "Williams kept talking, as if he hadn't heard the interruption. 'I am of the firm opinion that insanity is a hereditary disease of the brain. I have, for instance, seen several cases of babies delivered of women – I can hardly call them \"ladies\" – who are inmates here at Bethlehem. These babies were steeped in madness as they lay in the womb, and my attendants have told me that they have acted like devils from the moment they were born.'\n", "\n", "It occurred to Sherlock that any baby born in a place like Bedlam, with all its screams and cries and the slamming of doors, would be likely to scream and cry themselves, and that was regardless of whether their mothers were properly able to take care of them, but he kept quiet. He suspected that Dr Williams did not like to be interrupted when he was pontificating.\n", "\n", "'Under my predecessor, the esteemed Doctor Hood,' Williams continued, 'insanity was treated – if you can call it that – with drugs and with rest and with seclusion. This is not an approach that I believe works well. I would rather tie a patient down constantly than keep him always under the influence of a powerful drug. I have known cases of chronic insanity benefit materially – although not be cured entirely, of course – by a prolonged period of time in a padded cell. I have also observed several patients who were destructive and aggressive become as meek as lambs after several hours restrained in baths of warm water. This is _my_ approach, and you will experience its benefits yourself. I hope that in time you will recover from the mania which you have so obviously displayed, and that you will be able to be released into society again.' His gaze met Sherlock's. 'Now, do you have any questions?'\n", "\n", "Sherlock's brain raced. How could he best convince Dr Williams that he wasn't mad?\n", "\n", "'Am I displaying signs of mania now?' he asked quietly.\n", "\n", "'You appear to be in a placid phase of your insanity,' Williams said. 'Mania goes in cycles.'\n", "\n", "'Then how do you know that I _was_ displaying signs of mania?'\n", "\n", "'I have the reports of the policemen and other members of the public at the scene.'\n", "\n", "'If I do _not_ display any further signs of mania,' Sherlock went on carefully, 'then how long will it be before you decide that I am either cured or that I was never mad at all?'\n", "\n", "'As to the first,' Williams said, 'I cannot observe you at all times. Just because you display no signs of mania now, that does not mean that at three o'clock tomorrow morning you will not be raving in your cell and banging your head against the walls. As to the second – well, of _course_ you are mad to begin with. Why would you have been sent here otherwise?'\n", "\n", "Before Sherlock could respond to this obviously stupid remark, Williams rang the bell that sat beside the ledger.\n", "\n", "'If madness is hereditary,' Sherlock said desperately, hearing the door opening behind him, 'then how _can_ it be cured? Surely by that definition people are born with it, in the same way that they might be born with red hair.'\n", "\n", "Williams stared at Sherlock as if he was disappointed by him. 'Ah, a display of argumentativeness,' he murmured. 'A classic sign of incipient mania.' He made a note in the ledger. 'Take him away,' he said, without looking up.\n", "\n", "A hairy hand closed over Sherlock's shoulder. 'Don't make any trouble,' the attendant advised. 'Remember what I said.'\n", "\n", "Sherlock allowed himself to be pushed out of the room, across the hall, through the grille gate and along the gallery. Despair filled him. Unless something happened, unless Amyus Crowe could get him out, then he might be incarcerated there forever. How could Sherlock persuade a man like Dr Williams that he was sane when Williams believed that insanity was inherited, and that even arguing was a sign of madness? Nothing that Sherlock could do would change his mind!\n", "\n", "Padded cells. Being tied down. Restrained in a warm bath for hours on end. Was this what his future held for him? Was this the shape of the rest of his life?\n", "\n", "Not if he could help it.\n", "\n", "As he was led along the gallery, past the caged fires and the slitted windows, past the various men who paraded up and down or just stood around motionless, his brain was racing. If he couldn't rely on the medical profession to realize that he was sane, and if he couldn't rely on Amyus Crowe or brother Mycroft to get him out, then it was left to him. He had to escape by himself.\n", "\n", "'You're allowed free association wiv the other inmates,' the toothless attendant said. 'Until lights out, that is, then you're locked in your cell. Sorry, I mean your _room_. Your palatial accommodation.' He laughed. Sherlock could smell something rank coming from his mouth: a combination of tooth decay and tobacco. 'Food trays will be bought along later. If there's any trouble – if you start a fight, or start trying to cut yourself – then we'll lock you up early. Understand?'\n", "\n", "'I understand,' Sherlock said.\n", "\n", "'Good lad. I don't think you're goin' to be any trouble at all, are you? I got a sense about these things. Be good and the years will just fly past.'\n", "\n", "He was still laughing as he got to the grille at the end of the gallery.\n", "\n", "Sherlock gazed around. There were six other inmates in the gallery. Two of them were walking up and down like mechanical toys, three were playing dice and the sixth was sitting against the wall, arms around his knees, rocking to and fro. The man who had been toasting the mouse earlier had vanished back into his cell, presumably to eat his feast in comfort. There were also two attendants: one at each end of the gallery. They were standing in a position where they could get a clear line of sight all the way down, but they looked bored. As long as a fight didn't break out, Sherlock didn't think they would be interested.\n", "\n", "Casually, he wandered back into his room. His _cell_. The moment he was out of sight of the attendants he slipped his jacket off. He ran his hands along the sleeves until he located a tear. It had probably been caused by whatever fracas he had got into just before he had been taken away to Bedlam.\n", "\n", "Carefully he pulled at a thread until it came loose. He followed the thread along the sleeve, pulling at it all the time, until he found the other end. A quick tug and it was away: a section of thread about a foot long. The material of the jacket sleeve was wrinkled now, pulled out of shape, but that didn't bother him too much. Working rapidly but carefully, he managed to get another five threads loose. Once he had them all in his hand he put the jacket down and tied the threads together so that he had two long strands. Cautiously he tugged at them. The knots held firm.\n", "\n", "It was a start, at least.\n", "\n", "If there was one thing Sherlock was sure about, it was that he wasn't going to spend the next few years in the Bethlehem Hospital. One way or the other, he was getting out.\n", "\n", "Sherlock ambled out of his straw-matted, brick-lined room, the threads from his jacket held bundled in his hand. He leaned against the door frame, as if watching what was going on in the corridor, but he was waiting for something. He was waiting for a distraction, and given that he was in a lunatic asylum he was fairly sure that a distraction was going to come along soon.\n", "\n", "It took nearly half an hour, but, just as he was about to give up, one of the dice players suddenly stood bolt upright. His hand was groping inside his jacket pocket.\n", "\n", "'My watch,' he snarled. 'It's gone!' He glowered at the man nearest him. 'It was you, wasn't it? You fell against me a few minutes ago. You must've taken it then! You black dog!'\n", "\n", "A fight broke out, both men rolling on the flagstones of the gallery, trying to claw each other's eyes out, while the gallery quickly filled up with shouting observers lured out of their rooms by the noise. The attendants rushed from opposite ends of the gallery, brandishing their clubs, hitting out to the left and to the right to clear a way through the growing crowd.\n", "\n", "Sherlock slipped to the other side of his door: the outside. The large metal bolt was at head height. Taking one thread he tied it around the handle of the bolt and then trailed it up the door and over the top, pressing it into a gap between two planks. The loose end now hung down on the inside of the door. When the door was closed and locked, it would be on Sherlock's side.\n", "\n", "The second thread he also tied around the handle of the bolt, but this time he trailed it horizontally, towards the hinges. He passed the thread through the gap between the door and the frame, letting it rest on one of the hinges so that it didn't fall. Again, he passed it through to the inside of the door, catching it on one of the rivets that held the door together so that it didn't slip down.\n", "\n", "He checked over his shoulder. Nobody was watching. The attendants were laying into the fight now, splitting people up and cracking heads.\n", "\n", "Sherlock bent down and rubbed his hands on the flagstones, picking up as much dirt and dust as he could. Quickly he rubbed his hands along the two threads, blackening them and making them less visible. He imagined the attendants sliding the bolt across, flicking the handle down and locking him in for the night. If he was lucky they would do it automatically – _slide, across, down_ – and the threads would be intact and unnoticed. And maybe – maybe – that would be the start of his escape.\n", "\n", "Finished for the time being, he moved out into the gallery to watch the fight being broken up. There was blood on heads, on the clubs and on the floor.\n", "\n", "'In your cells, all of you!' one of the attendants called. 'Now!'\n", "\n", "'What about food!' someone yelled.\n", "\n", "'No food tonight. You've lost that privilege. Nothing till breakfast for you animals, and you'll like it or lump it!'\n", "\n", "As the attendants began pushing people into their cells and bolting the doors, starting at the far end of the gallery, Sherlock glanced sideways. A man was standing in the doorway of the next cell along. His clothes were threadbare: so dusty that although they had started off different colours they were all now approaching the same shade of grey. His beard and hair were grey. Even his skin was grey.\n", "\n", "He glanced over at Sherlock. His eyes weren't grey: they were a faded, watery blue.\n", "\n", "'Do I detect a new arrival?'\n", "\n", "'That's right. I'm Sherlock. Sherlock Holmes.'\n", "\n", "'My name is Richard Dadd. I am exceptionally pleased to meet you.' He extended a hand towards Sherlock. As Sherlock shook it, he noticed that Dadd's hand was coloured in various shades of green and blue.\n", "\n", "Dadd noticed the direction of his gaze. 'They allow me to paint,' he explained. 'They provide me with canvas and oils and turpentine. It makes the days pass quicker. The endless days.'\n", "\n", "Sherlock gazed at Dadd. 'You seem . . . normal.'\n", "\n", "Dadd smiled. 'You mean sane?' He shrugged. 'I believe that I am. Doctor Williams believes that I am not. We have a difference of opinion. Unfortunately, his opinion counts for more than mine does in this establishment.'\n", "\n", "The attendants had moved to about halfway between the end of the gallery and Sherlock's cell now. Every few seconds another door would thud closed, and the bolt would be shot across, locking it. Within a few moments he would be locked away as well. Alone. Desperate for human conversation, if only with a lunatic, he asked: 'What . . . what happened . . . to get you locked up here?'\n", "\n", "'It's very simple, and very sad. My father was possessed by the very Devil himself. I killed him in Cobham Park. I stabbed him to death.'\n", "\n", "Sherlock felt as if someone had doused him in cold water. 'And that's why you are here?' he heard himself saying.\n", "\n", "'That,' Dadd admitted, 'and the fact that I was apprehended on my way to murder the Austrian Emperor. It's all a tragic misunderstanding, but Doctor Williams refuses to see it as such.'\n", "\n", "The attendants would be with them in a few moments. The gallery was becoming quieter and quieter as the inmates were locked away, one by one.\n", "\n", "'Take my advice,' Dadd said urgently.\n", "\n", "'What's that?' Sherlock asked.\n", "\n", "'Beware the Lady who walks in the night.'\n", "\n", "'The Lady?' Sherlock asked, confused.\n", "\n", "'She walks the galleries late into the night on noiseless feet,' Dadd confided, leaning towards Sherlock with a serious expression on his face. 'They say she was a serving girl who fell in love with the son of the man in whose house she worked. When this son left home he gave her a guinea coin – pressed it into her hand as a gift. He got into his coach and drove away, but the next thing the family knew she was chasing after the coach, screaming. The family ran after her, but the shock of the son leaving had driven her senses from her. She was committed here, to Bedlam, and spent several years here, and all that time she clutched that guinea in her fist and would not let it go, whatever the proffered compensation. She died with it still in her hand, they say, and her last request was that she be buried with the coin, but the story goes that a heartless attendant prised it from her cold, dead fingers. And so her spirit roams the corridors of this ghastly place every night since, forever searching for that lost coin, that gift from the man she loved and who loved her not. Her fingers clutch our trinkets in place of what she has lost.'\n", "\n", "'That's rubbish,' Sherlock said, but he could hear the uncertainty in his own voice. He didn't believe in ghosts, but there was something about Dadd's serious expression, and the conviction in his voice, that gave Sherlock pause.\n", "\n", "'Perhaps so,' Dadd said. 'Perhaps so, but be watchful nevertheless. There _are_ strange things that walk these galleries at night. Believe me. The boy who was in that room before you – he disappeared. Vanished suddenly and noiselessly. My suspicion is that the Lady came looking for her coin, and he saw her, so she took him instead.'\n", "\n", "The attendants had reached Dadd by now. He nodded his head to them courteously, and backed into his room. 'Gentlemen,' he said as he went. 'Goodnight to you.'\n", "\n", "Next it was Sherlock's turn. He backed into his room before they got to him. The thud of the door closing, and the metallic rattle of the bolt sliding shut, were the two most terrible sounds he had ever heard.\n", "\n", "He waited until the attendants had moved on, and he had heard the door and bolt on the next room thudding home, before he checked the threads. They were both intact. He tugged experimentally on both of them, taking up the slack. They seemed to be all right. Maybe, just maybe, his plan would work.\n", "\n", "But he had to wait until well after midnight to try it out.\n", "\n", "Aware that his stomach was empty and that he wasn't going to get anything for at least another twelve hours, he sat on the straw-covered floor and rested his back against the cold, dank bricks. How did people survive here, night after night? How did they manage to keep . . . sane? The moment the word popped into his mind he found himself laughing. Of course. Most of them weren't sane. _Most_ of them. But Sherlock was, and he suspected that at least a handful of other people imprisoned in Bedlam were sane as well. Maybe they were eccentric, maybe they had opinions that were abhorrent to politicians or Church leaders, but that didn't make them mad.\n", "\n", "He must have fallen asleep while he was thinking, because the next thing he knew, the only light coming in through the slitted window was the pale, white light of the moon. He watched as the distorted rectangle it cast slid down the wall, like a piece of paper stuck to the bricks with treacle.\n", "\n", "The next thing he knew, the rectangle of light was on the floor. He must have slept again for a while. His shoulders ached from the cold of the wall, and the muscles of his legs felt weak and tingly.\n", "\n", "And someone was watching him through the wooden hatch in the door.\n", "\n", "He could see light silhouetting a head, and he could sense eyes, malicious eyes, staring at him intently. He didn't move, didn't speak. Eventually, with a soft squeak, the hatch closed again.\n", "\n", "It wasn't one of the attendants: that much he was sure of. They wouldn't have bothered being quiet. They would have just slammed the hatch open, taken a look and then slammed it closed again. Whoever had been watching Sherlock through the hatch hadn't wanted him to know about it.\n", "\n", "The sensible thing would have been to have waited for a while before making his move, but he was burning with curiosity now. He wanted to know who it was that had been interested in him.\n", "\n", "Silently he climbed to his feet and crossed to the door. He cautiously felt for the two threads that he'd left there earlier, trailing from the handle of the bolt. They were fragile, thin, and he was worried that they might have been disturbed by the opening of the hatch, but after a few moments of groping around he found first one, and then the other.\n", "\n", "He had to do the next bit very carefully. There was no room for error: he would only get one chance.\n", "\n", "The way the bolt was designed, it had to be rotated through a quarter-turn before the handle could slide past the brackets. One of the threads – the one that trailed over the door – he could use to rotate the bolt. If he was lucky. The other one he could use to pull the bolt back, out of its catch.\n", "\n", "Experimentally, he pulled on the thread that ran up and over the door. It gradually pulled taut. He tugged on it. Nothing. He felt a growing frustration churning in his chest. He wanted to pull hard, but if he did that then the thread might snap, or the knots might give. Maybe it was snagged on a rivet, or a splinter, or something. It might even have become caught up between the door and the frame when the door closed. Forcing himself to focus, Sherlock felt the tight band around his chest ease slightly. He pulled again on the thread. This time he felt something give, and from the other side of the door he heard a grating noise. In his mind he could see the thread pulling on the handle of the bolt, but with the brackets stopping it from moving and with the handle offset, the only freedom of movement it had was for the bolt to rotate around its own longitudinal axis. So, reluctantly, it did.\n", "\n", "Sherlock had to judge the amount of rotation very carefully. If it rotated the bolt too much – if he ended up with the handle pointing directly upward – then it would not open. The only clear path the handle had was when it was pointed outward at ninety degrees to the door. If he pulled too far then there was no way to get the bolt down again. This was a one-time-only opportunity for freedom.\n", "\n", "Sherlock stopped pulling while there was still some play in the thread. He wanted to pull further, but he knew he shouldn't. Time to try the other thread now, and pray that it worked.\n", "\n", "Keeping the tension on the first thread, he pulled on the second one, which ran horizontally around the edge of the door. If he'd worked things out correctly then this one should pull the bolt back along the door, out of the catch. _If_ he had worked things out correctly.\n", "\n", "There was some resistance, but the thread moved, and he could feel an increase in tension in the first thread, the vertical one. On the other side of the door he could hear the grating of metal against metal as the bolt slid back. Elation filled him. He stopped breathing, in case the movement of his chest disturbed the delicate balance of the threads.\n", "\n", "After a minute or so of gradual movement, the thread went tight. The bolt couldn't move any more. If Sherlock was right, then it had been pulled completely back, and the door was unlocked.\n", "\n", "He pushed against the wood.\n", "\n", "Nothing. The door didn't move.\n", "\n", "He pushed again, harder.\n", "\n", "This time, the door shifted slightly. He'd forgotten how heavy it was! He threw his weight against it, and the door opened an inch.\n", "\n", "He braced his boots against a gap between the flagstones of his cell and pushed with his shoulder.\n", "\n", "The door swung open.\n", "\n", "He caught it before it could go too far, and slipped through the gap and into the gallery.\n", "\n", "Firelight flickered along its length. The windows were thin rectangles of blackness. Silence, apart from the crackle of burning coals.\n", "\n", "A figure moved silently down the corridor, away from him. It was a woman, dressed entirely in black. Her head was covered in a shawl, and as she came level with each door she paused for a moment and gazed towards the cell, then moved on down the gallery. He couldn't see her feet; she seemed to glide noiselessly across the floor.\n", "\n", "Sherlock realized that she was gliding in the opposite direction from the grille that closed off the space between the gallery and the entrance hall. He suspected that if he was going to get out then he had to go back, towards the entrance. Part of him desperately wanted to follow the woman in black – the _ghost_ in black, part of his mind said – but the more sensible part wanted to get to freedom. He didn't have a plan for getting past the grille, but at least he'd managed to get out of his cell. That was an accomplishment in its own right.\n", "\n", "With a last, regretful glance along the gallery, where the woman in black had stopped outside one of the cells, Sherlock moved in the opposite direction.\n", "\n", "He could hear a mixture of sounds coming from the cells as he moved rapidly along. From some of them came heavy snoring, from others muffled sobs and from the remainder either silence or voices praying. He wished he could do something for them, but he wasn't in a position to lead a mass escape attempt, and even if he could he was in no position to distinguish between the sane and the mad. He had to save himself.\n", "\n", "He got to the grille at the end of the gallery. The hall beyond was in shadow. He had a vague idea that he might be able to pick the lock, or take the door off its hinges, or even hide behind one of the enormous flowerpots until morning and sneak out behind the backs of the attendants, but he was amazed to see that the grille was unlocked. He glanced around, expecting a trap, but nobody jumped out at him. He pulled the door open and slipped into the hall.\n", "\n", "Freedom.\n", "\n", "Almost.\n", "\n", "He kept to the shadows around the edge of the hall, rather than crossing the tiled expanse of the centre, until he came to the double doors that led outside. Nervously he pushed them open, expecting at any moment that an alarm bell would be sounded, or that somebody would shout after him, but nothing happened.\n", "\n", "The air outside was the freshest he could ever remember breathing. It was like drinking clear, cold water from a stream.\n", "\n", "It was still night, and the road on the other side of the wall was quiet. He looked around, getting his bearings. If he could make it to the road then he could hail a cab and persuade the driver to take him . . . where? Amyus Crowe hadn't booked them into a hotel, and he didn't know where the big man had gone. He supposed he could head for the Diogenes Club. It was the only place that Crowe might think to use as a rendezvous.\n", "\n", "He ran down the steps and on to the path that led away from Bedlam.\n", "\n", "'Oy!'\n", "\n", "The voice was loud, aggrieved. He wanted to run, pell-mell, down the path to freedom, but something made him turn around.\n", "\n", "The toothless attendant was standing on the steps, club in one hand and a whistle in the other. 'You come right back 'ere, son, or I'll call the Peelers, so I will. If you come now I promise I won't break any bones. If I have to get the police to get you back it'll reflect badly on me, and that means I'll take it out on you. I guarantee you'll walk crooked for the rest of your short life.'\n", "\n", "Sherlock was about to tell the attendant to go to hell, and run, but someone yelled out from inside the hall. The attendant turned to call back. 'It's all right – I got 'im out 'ere!' he shouted. He turned back, whistle coming up to his mouth, but he looked at Sherlock and the hand holding the whistle slowly dropped down to his side again. His expression was a mask of confusion.\n", "\n", "'If there's any breakin' of bones to be done around here,' a deep, deceptively calm voice said, 'then I believe I have priority. And, by the way, considerable experience as well.'\n", "\n", "Sherlock didn't have to turn his head to know that Amyus Crowe was standing directly behind him, close enough that if Sherlock stepped back then he knew he'd bump into him.\n", "\n", "''E's an escaped madman!' the attendant exclaimed.\n", "\n", "'I don't think so,' Crowe observed. 'I have in my pocket a piece of paper signed by three separate doctors, all confirming the sanity of this boy. I think a mistake has been made, a serious mistake, and if you don't want it to reflect on you then you should just let us walk away now.'\n", "\n", "'We can't,' Sherlock said quietly.\n", "\n", "'Why not?'\n", "\n", "He sighed. 'There's something I have to do. Inside. I have to talk to the Resident Physician.'\n", "\n", "'Son, there're times when life offers you a free gift.' Crowe's voice was urgent, insistent. 'This is one of those times. If we walk away now, you're safe. If we go inside, I can't guarantee what will happen. They might find a way of keeping you.'\n", "\n", "'I know, but there're more important things at stake here. I need to see the Resident Physician.'\n", "\n", "This time it was Crowe who sighed. 'I gotta say, life as your tutor is never boring.' He raised his voice. 'You – the man with the club and the badly fittin' uniform. I want to see the Resident Physician. Tell him I'll be waiting in his office for an explanation as to why he saw fit to imprison a perfectly sane boy.' Whispering now, as the attendant gaped blankly at them, he said to Sherlock: 'Lead the way, son. Let's let him find us in his office, with me sittin' behind his desk. It'll keep him off balance.'\n", "\n", "Sherlock led Crowe past the attendant, who ran past them, into the hall, and across to the door that led to the offices and administrative areas. He looked for a moment as if he was going to bar their way, but instead he ran off down the corridor.\n", "\n", "'The Resident Physician sleeps on the premises,' Crowe rumbled as Sherlock led the way into the oak-lined office. 'That's one thing I found out about this institution.' He looked around. 'Nice place. He obviously gets paid well.'\n", "\n", "'Who pays him?' Sherlock asked. 'Who funds this place?'\n", "\n", "'As I understand it, families pay for their loved ones to be \"looked after\", whether they need it or not. There're rumours of women bein' sent here because they wouldn't get married, or wanted to marry someone unsuitable, or had gotten themselves married but didn't love their husbands. Obvious sign of madness, I'm sure you'll agree.'\n", "\n", "'But there _is_ such a thing as _real_ madness, isn't there?' Sherlock asked.\n", "\n", "'There is,' Crowe agreed, 'but I wouldn't bet on the doctors here recognizing it unless it ran up an' bit them on the nose.' He frowned. 'Which, bein' madness, it probably would.'\n", "\n", "'So,' Sherlock said, his thoughts suddenly catching up with what had been said, 'who paid for _me_ to be incarcerated here?'\n", "\n", "'That's the six thousand dollar question.' Crowe walked over to the other side of the desk and sat down. 'Answer is, I don't know, but someone did. You probably saw that I got involved in an altercation. You started actin' strangely, but before I could extricate myself from my situation you'd been carted away. Whoever did this had a carriage an' a doctor ready an' waitin'. Come and join me, by the by. Stand by my shoulder.'\n", "\n", "'So what happened?' Sherlock asked, moving to stand behind Crowe. 'What did I do?'\n", "\n", "'You went wild, throwin' yourself on the ground an' shoutin' about fire an' birds an' suchlike. You were out of control. Never seen anythin' like it in my life – 'cept once when Ginny and I were on the boat comin' over here an' a passenger ran across the deck, screamin' that he couldn't stand the waves and the sky starin' at him any more. Threw himself over the railin's. The Captain turned around to try an' find him, but he'd gone. Drowned.'\n", "\n", "Sherlock felt his breath catch in his throat. 'What _made_ me act like that?'\n", "\n", "'I suspect that somethin' was added to your drink, or sprayed in your face. Remember that substance in the pocket of the dead man in the Diogenes Club some time ago – the spray we think caused your brother to have a blackout while still standin'? I think you'll find whatever was used on you was a similar thing, but designed to cause temporary hallucinations, rather than blackouts.'\n", "\n", "'But why?'\n", "\n", "'I don't rightly know, but my money is on the Paradol Chamber. You've stepped in their way twice now and managed to stop their international criminal activities – once with Baron Maupertuis an' once in Russia. I think they want to get you out of the way.'\n", "\n", "Sherlock was about to ask how Crowe had found him when the door burst open and Dr William Rhys Williams rushed in. He was wearing an embroidered dressing gown over a nightshirt, and had a tasselled velvet cap on his head. He was furious: red in the face and wide-eyed.\n", "\n", "'What in heaven's name do you think you are doing, facilitating the escape of an inmate of this institution? I should have you horsewhipped!'\n", "\n", "'Is that an approved medical treatment?' Crowe rumbled. 'Or just somethin' you enjoy as a recreational activity?'\n", "\n", "'Get out from behind my desk!' Williams shouted.\n", "\n", "'Not your desk for much longer,' Crowe said calmly.\n", "\n", "'What do you mean?'\n", "\n", "'I know your General Medical Council ain't been around for long, but I doubt they'd look too kindly on one of their members accepting sane people into a lunatic asylum for cash.'\n", "\n", "'This child is not sane,' Williams snapped. 'I examined him myself.'\n", "\n", "'I have three doctors who say he is,' Crowe replied, holding up an envelope. 'I'd be happy to set them against you in a court of law and see who comes out ahead, but before I do that my friend here has somethin' to say.' He looked up at Sherlock. 'All yours, son.'\n", "\n", "'I saw something,' Sherlock said, trying to control his breathing. Looking at Williams's florid face made him feel sick. Just a few short hours ago, this man had said that Sherlock was obviously insane.\n", "\n", "'Saw what?' Williams asked. 'This is a lunatic asylum. All kinds of things happen in here that don't happen in the world outside.'\n", "\n", "'I saw a ghost,' Sherlock said calmly.\n", "\n", "Williams glanced at Crowe and raised an eyebrow, as if to say _I told you so_. 'A ghost?' he said in a reasonable voice. 'Please, tell us more. Did it walk through walls?'\n", "\n", "'No,' Sherlock replied, 'and that's what made me realize that it wasn't really a ghost. It was meant to look like one – dressed all in black, and supposedly the spirit of a poor servant girl who died here – but what ghost needs to leave a door open so that it can move about, or use a hatch to look at someone in their cell?'\n", "\n", "'You think it was someone dressed up?' Crowe asked from beside him, face alert. 'Why?'\n", "\n", "'There are people here who have privileges. I suspect that long-term inmates get to furnish their cells and wear their own clothes. I think that long-term inmates who aren't obviously dangerous can be quite comfortable here. And I think that one of the attendants is stealing from them – getting into their cells while they are asleep and stealing stuff, like watches, or coins.' He paused, remembering the fight between the dice players. 'I've only been here a day and I've noticed that inmates are losing possessions. They're like sitting ducks – vulnerable, easy to take advantage of.'\n", "\n", "'Why on earth would any such thief dress as a ghost?' Dr Williams said dismissively.\n", "\n", "'If someone who has been diagnosed as being insane says that a ghost has stolen things from them, who will believe them?' Sherlock asked simply.\n", "\n", "'And has anything else strange happened?' Crowe asked. He was talking to Sherlock, but his face was stern as he stared at Williams.\n", "\n", "'A boy who was in my cell before me died,' Sherlock said. 'They said he'd seen the ghost, but I think he'd worked it out.'\n", "\n", "'Had he?' Crowe's gaze was fixed on Williams. 'Or is there something goin' on here worse than theft?' He stood up abruptly. 'We'll be takin' our leave of you, Doctor Williams. I think you can expect a visit from the General Medical Council and the police in the near future. I think you can expect them to look into any unexplained deaths that have occurred here – especially of young people. And I think if you don't cooperate fully with them, then you'll hang along with whoever actually _is_ responsible – assumin', of course, that you're not the person wearin' the ghost costume an' stalkin' these corridors at night.'\n", "\n", "'I know nothing about this,' Williams said, but his face was as white as if he had seen a ghost himself. Perhaps, Sherlock thought, he'd glimpsed a vision of his own future, and he didn't like what he'd seen.\n", "\n", "'It stops,' Crowe said as he walked out from behind Williams's desk and past the doctor. 'It stops _now_.'\n", "\n", "'Do you think things in there will change?' Sherlock asked as they walked out of the building and into the cool, fresh air.\n", "\n", "'I'll make sure they do,' Crowe replied. 'Sad to say, son, but things like this go on all over the place. Wherever there're people in a position of power an' other people who are vulnerable, there's theft, an' abuse, an' worse.' He shook his head. 'It ain't within the gift of a man to change the world. All he can do is change the things he sees around him. If enough people do that, then maybe the world will change anyway.' He glanced at Sherlock. 'I'll talk to your brother. He can pull some strings – get the place checked over officially. An' I'll make sure they know what they're lookin' for.'\n", "\n", "Sherlock nodded. 'Thank you.'\n", "\n", "They walked on in silence for a few moments.\n", "\n", "'That was good figurin' out, by the way,' Crowe said.\n", "\n", "'What was?'\n", "\n", "'The bit about the ghost – workin' out that only livin' people need open doors.'\n", "\n", "Sherlock smiled. 'It just seems obvious. A ghost that can't walk through walls, or bars, isn't a ghost at all. And that's why I can't believe in ghosts, by the way.'\n", "\n", "Crowe raised an enquiring eyebrow. 'Go ahead – I'm all ears.'\n", "\n", "'Well, we assume that ghosts can walk through walls, but they apparently still need to walk on floors. People say they've seen ghosts on stairs, or in first-floor bedrooms, or wherever. It doesn't make any sense. If walls aren't any barrier to ghosts then floors shouldn't be either – they should just fall straight through them. Or, rather, they shouldn't be able to climb up stairs in the first place. Maybe, logically, there's something about the _ground_ that means they can't move through it, the ground being natural, but if they can move through vertical barriers like walls then they can move through horizontal barriers like floors, and if they _can't_ move through horizontal barriers then they can't be ghosts.'\n", "\n", "Crowe considered for a moment. 'I like your style of thinkin'. Most people argue for or against the existence of ghosts on a spiritual basis. You're applying rigorous logic. Are you doin' this to everythin' in your life?'\n", "\n", "'Bit by bit.'\n", "\n", "'Try not to turn your attention to religion _just_ yet. Remember, you still have to live in your uncle's house, an' I suspect that his heart wouldn't stand the strain if you tried to persuade him logically that God don't exist.'\n", "\n", "Crowe headed towards a carriage that was waiting patiently for them. Sherlock hung back.\n", "\n", "'Can we trust it?' he asked uncertainly.\n", "\n", "'As much as we can trust anything,' Crowe rumbled. 'It's the cab I took to get here. To be on the safe side, I waited for three to pass before I hailed it.' He placed a hand on Sherlock's shoulder. 'You're spooked, son, an' that's natural. The Paradol Chamber have taken a shot at you, an' it blew up in their face. I don't think they'll try anythin' else for a while. If nothin' else, this was a warnin'. They want you to know they're watchin' you, an' they don't want you interferin' in their plans again.'\n", "\n", "Sherlock felt something harden within his head. 'Then I don't have a choice, do I?' he asked.\n", "\n", "Crowe just cocked an enquiring eyebrow.\n", "\n", "'If I want to walk safely in the streets,' Sherlock said grimly, 'then I have to bring the Paradol Chamber down. I have to crush them so they never threaten anybody else again.'\n", "\n", "Crowe nodded. 'I reckon,' he said, 'that's a logical course of action to take.'\n", "**AUTHOR'S NOTE**\n", "\n", "The text that forms the majority of this story was originally written for the third Young Sherlock Holmes adventure – _Black Ice_. It formed a self-contained section just after Sherlock is attacked by a steel-clawed falcon in the Passmore-Edwards Museum and just before he heads off to Russia. It was removed because it slowed the story down, and because it didn't have very much to do with the rest of the plot. I always regretted its loss, so I present it here as a short story in its own right. The action now takes place between the end of _Black Ice_ and the beginning of the fourth Young Sherlock Holmes adventure, _Fire Storm_.\n", "\n", "Sherlock's brief imprisonment in the madhouse known as 'Bedlam' (or, more properly, the Bethlehem Hospital) is as accurate as I could make it. Actually, I could have put a lot more detail in there, but I wasn't sure that a full-blown description of a London madhouse of the 1860s was entirely appropriate for a story like this. They weren't nice places. Anyway, the books I used for research were:\n", "\n", "_Bedlam: London and Its Mad_ by Catharine Arnold (Simon & Schuster, 2008)\n", "_Bedlam: London's Hospital for the Mad_ by Paul Chambers (Ian Allan Publishing, 2009)\n", "\n", "Richard Dadd, the artist who engages Sherlock in conversation in the asylum, was indeed a patient at Bedlam for a number of years. He was, at one stage, moved to the newly opened Broadmoor Criminal Lunatic Asylum, but I'm assuming in this story that he was moved back to Bedlam for a while – possibly for good behaviour.\n", "\n", "The building occupied by the Bethlehem Hospital is now the Imperial War Museum in South London. My grandmother used to live just around the corner from it, and I have distinct memories as a child of being taken through the grounds, past the building, and looking up at it nervously, knowing that it had once been inhabited by lunatics. Apparently the staff of the museum still don't like going down into the basement to the storerooms. They say there's a 'feeling' about the place. Sherlock wouldn't believe in 'feelings', but me? I'm not so sure . . .\n", "\n", "Andrew Lane\n", "\n", "**ABOUT THE AUTHOR**\n", "\n", "Andrew Lane is the author of some twenty previous books. Some are original novels set in the same universes as the BBC TV programmes _Doctor Who_ , _Torchwood_ and _Randall and Hopkirk (Deceased)_ , some are contemporary novels written under a pseudonym, and some are non-fiction books about specific film and TV characters (notably James Bond, and Wallace & Gromit). He has also written for the _Radio Times_ and its US equivalent, _TV Guide_. Andrew lives in Dorset with his wife, his son and a vast collection of Sherlock Holmes books, the purchase of which over the past twenty years is now a justifiably tax-deductible expense.\n", "_Also by Andrew Lane_\n", "\n", "Young Sherlock Holmes: Death Cloud\n", "\n", "Young Sherlock Holmes: Red Leech\n", "\n", "Young Sherlock Holmes: Black Ice\n", "\n", "Young Sherlock Holmes: Fire Storm\n", "\n", "This electronic edition first published 2011 by Macmillan Children's Books \n", "a division of Macmillan Publishers Limited \n", "Pan Macmillan, 20 New Wharf Road, London N1 9RR \n", "Basingstoke and Oxford \n", "Associated companies throughout the world \n", "www.panmacmillan.com\n", "\n", "ISBN 978-1-4472-1287-4 EPUB\n", "\n", "Copyright © Andrew Lane 2011\n", "\n", "The right of Andrew Lane to be identified as the author of this work has been asserted by him in accordance with the Copyright, Designs and Patents Act 1988.\n", "\n", "You may not copy, store, distribute, transmit, reproduce or otherwise make available this publication (or any part of it) in any form, or by any means (electronic, digital, optical, mechanical, photocopying, recording or otherwise), without the prior written permission of the publisher. Any person who does any unauthorized act in relation to this publication may be liable to criminal prosecution and civil claims for damages.\n", "\n", "A CIP catalogue record for this book is available from the British Library.\n", "\n", "Visit **www.panmacmillan.com** to read more about all our books and to buy them. You will also find features, author interviews and news of any author events, and you can sign up for e-newsletters so that you're always first to hear about our new releases.\n", "\n" ] } ], "source": [ "print(book[2][\"text\"])" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# from transformers import LlamaForCausalLM, LlamaTokenizer\n", "from transformers import AutoModelForCausalLM, AutoTokenizer\n", "import torch\n", "import os\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{0: '32GB',\n", " 1: '32GB',\n", " 2: '32GB',\n", " 3: '32GB',\n", " 4: '32GB',\n", " 5: '32GB',\n", " 6: '32GB',\n", " 7: '32GB'}" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def get_max_memory():\n", " \"\"\"Get the maximum memory available for the current GPU for loading models.\"\"\"\n", " free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3)\n", " max_memory = f'{free_in_GB-6}GB'\n", " n_gpus = torch.cuda.device_count()\n", " max_memory = {i: max_memory for i in range(n_gpus)}\n", " return max_memory\n", "\n", "get_max_memory()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Loading checkpoint shards: 100%|██████████| 3/3 [00:26<00:00, 8.88s/it]\n", "/share/ninglu_shao/envs/snl/lib/python3.10/site-packages/transformers/generation/configuration_utils.py:362: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0.9` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`. This was detected when initializing the generation config instance, which means the corresponding file may hold incorrect parameterization and should be fixed.\n", " warnings.warn(\n", "/share/ninglu_shao/envs/snl/lib/python3.10/site-packages/transformers/generation/configuration_utils.py:367: UserWarning: `do_sample` is set to `False`. However, `top_p` is set to `0.6` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `top_p`. This was detected when initializing the generation config instance, which means the corresponding file may hold incorrect parameterization and should be fixed.\n", " warnings.warn(\n" ] } ], "source": [ "model = AutoModelForCausalLM.from_pretrained(\n", " MODEL_NAME,\n", " cache_dir=MODEL_CACHE_DIR,\n", " device_map=\"auto\",\n", " torch_dtype=torch.float16,\n", " max_memory=get_max_memory(),\n", ")\n", "tokenizer = AutoTokenizer.from_pretrained(\n", " MODEL_NAME,\n", " cache_dir=MODEL_CACHE_DIR,\n", " use_fast=False,\n", ")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\t\"Aaron Aaron ( or ; \"\"Ahärôn\"\") is a prophet, high priest, and the brother of Moses in the Abrahamic religions. Knowledge of Aaron, along with his brother Moses, comes exclusively from religious texts, such as the Bible and Quran. The Hebrew Bible relates that, unlike Moses, who grew up in the Egyptian royal court, Aaron and his elder sister Miriam remained with their kinsmen in the eastern border-land of Egypt (Goshen). When Moses first confronted the Egyptian king about the Israelites, Aaron served as his brother's spokesman (\"\"prophet\"\") to the Pharaoh. Part of the Law (Torah) that Moses received from\"\tAaron\n", "\n" ] } ], "source": [ "with open(\"/share/ninglu_shao/code/Citation/psgs_w100.tsv\", \"r\") as f:\n", " for idx, line in enumerate(f):\n", " if idx == 0:\n", " continue\n", " break\n", "\n", "print(line)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
idtexttitle
01Aaron Aaron ( or ; \"Ahärôn\") is a prophet, hig...Aaron
12God at Sinai granted Aaron the priesthood for ...Aaron
23his rod turn into a snake. Then he stretched o...Aaron
34however, Aaron and Hur remained below to look ...Aaron
45Aaron and his sons to the priesthood, and arra...Aaron
\n", "
" ], "text/plain": [ " id text title\n", "0 1 Aaron Aaron ( or ; \"Ahärôn\") is a prophet, hig... Aaron\n", "1 2 God at Sinai granted Aaron the priesthood for ... Aaron\n", "2 3 his rod turn into a snake. Then he stretched o... Aaron\n", "3 4 however, Aaron and Hur remained below to look ... Aaron\n", "4 5 Aaron and his sons to the priesthood, and arra... Aaron" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# read tsv file\n", "import pandas as pd\n", "df = pd.read_csv(\"/share/ninglu_shao/code/Citation/psgs_w100.tsv\", sep=\"\\t\")\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "df.to_json(\"/share/ninglu_shao/data/Citation/psgs_w100.jsonl\", orient=\"records\", lines=True)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "numpy.int64" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# get index 0 of df\n", "type(df.iloc[0][\"id\"])" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "pandas.core.series.Series" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df.iloc[0]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 21015324/21015324 [00:51<00:00, 408617.36it/s]\n" ] } ], "source": [ "# jsonlines\n", "import jsonlines\n", "from tqdm import tqdm\n", "\n", "tmp = []\n", "\n", "with jsonlines.open(\"/share/ninglu_shao/data/Citation/psgs_w100.jsonl\", \"r\") as f:\n", " for line in tqdm(f, total=21015324):\n", " tmp.append(line)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "tmp = [{'question': 'Who is the father-in-law of Basilina?', 'answer': 'Constantius Chlorus', 'context': [{'doc_id': 6844165, 'score': 83.51922, 'text': \"2016 the national championship was won by the regional team and in the variety rink bandy, a national title was obtained in 2014. West Kazakhstan Region West Kazakhstan Region (; ) is a region of Kazakhstan. Its administrative centre is Oral (also known as Uralsk and Ural'sk), a city of about 200,000 inhabitants. The region borders Russia and is near the Ural Mountains. The Ural River is the border between Asia and Europe and flows from Russia to the Caspian Sea through the region, meaning western West Kazakhstan is in Eastern Europe. West Kazakhstan region borders Aktobe Region to the\"}, {'doc_id': 6844174, 'score': 83.39622, 'text': 'Leo Armstrong, former principal of Weirsdale High School was the first principal. The school served students coming from elementary schools at Belleview, Florida, Summerfield, Florida and Weirsdale, Florida that served the communities of Belleview, Candler, East Lake Weir, Ocklawaha, Pedro, Summerfield, Sunset Harbor, and Weirsdale. The first class of 1956 graduated 33. In 1967, Marion County changed to the elementary, middle and high school organization and the school changed to grades 9 through 12. In August, 1975, a new Lake Weir High School was constructed on Maricamp Road in Candler with a student body in excess of 1200 students, which'}, {'doc_id': 6877491, 'score': 83.263626, 'text': 'AM suffered its last major re-adjustment of its units still under the Army tutelage. As part of this, the BA4 (Santana Air Base) was disbanded, with its aeronautical facilities being transferred to the Ministry of Communications to become the civil airport of São Miguel Island. With this disbandment, Lajes was re-designated \"No 4 Air Base (BA4)\". By this time, Lajes was already one of the major air bases of the AM, including the longest runway in the world and well developed support facilities that included a seaport and a military hospital. From 1945, it was open to civil air traffic,'}, {'doc_id': 7116549, 'score': 83.11453, 'text': \"almost a month of protest. The opposition decided to abandon protests after FSN's victory in the May elections. On 11 June, negotiations between the government and the remaining demonstrators failed. About 100 people, dissatisfied with the result of the dialogue between the government and the hunger strikers, started rioting in Victoria Square (Piața Victoriei) and closed in on Victoria Palace (Palatul Victoriei, the government's headquarters). Police, military police and army forces appeared, together with some armoured personnel carriers. The police pushed the demonstrators back to Calea Victoriei and retreated towards the Palace. 4:00 AM: The police forces attacked the hunger\"}, {'doc_id': 7143287, 'score': 82.79395, 'text': \"the church. The church during this period has been described as not particularly welcoming to newcomers, but this was especially so for persons of color. Some parishioners would not shake their hands during the peace, and all but told them their place was at St. Alban's. Two persons in particular helped to change this dynamic. One was Father Martin Gutwein, a curate under Fr. Frank Carthy, who had served in the Peace Corps and knew the family members of some of the new members and made them feel welcome. With his acceptance, some of the veteran members of the parish\"}]}, {'question': 'Where was the performer of song How Do You Sleep? (John Lennon Song) born?', 'answer': 'Liverpool', 'context': [{'doc_id': 3373467, 'score': 74.77792, 'text': 'just another day\" are directed at McCartney, the first lyric being a reference to the Beatles\\' 1965 song \"Yesterday\". The second lyric is a reference to McCartney\\'s hit single \"Another Day\", released in February 1971. Lennon initially penned the lyrics \"You probably pinched that bitch anyway\", as a reference to the many times McCartney had made claims that he was not sure if he \"nicked\" \"Yesterday\", having asked Lennon, Harrison, George Martin and others if they had heard that melody before. Although Lennon received the sole writing credit for \"How Do You Sleep?\", a contemporary account by Felix Dennis of'}, {'doc_id': 3373463, 'score': 72.40813, 'text': 'House in Washington, D.C., were later combined into one house and became the property of the U.S. government. Today they are the Blair-Lee House, used by the President as his guest house. Upon retirement he moved to the family home in Silver Spring, Maryland, where he died on 7 June 1897. Two U.S. Navy ships have been named in honor of Rear Admiral Samuel Phillips Lee, the destroyer , which was commissioned in October 1920 and lost by stranding in September 1923, and the research vessel (ex-AGS-31), which was in naval service between 1968 and 1974. Samuel Phillips Lee Samuel'}, {'doc_id': 3373464, 'score': 71.24425, 'text': 'How Do You Sleep? (John Lennon song) \"How Do You Sleep?\" is a song by English rock musician John Lennon from his 1971 album \"Imagine\". The song makes angry and scathing remarks aimed at his former Beatles bandmate and songwriting partner, Paul McCartney. Lennon wrote the song in response to what he perceived as personal slights by McCartney on the latter\\'s \"Ram\" album. The track includes a slide guitar solo played by George Harrison and was co-produced by Lennon, Phil Spector and Yoko Ono. John Lennon wrote \"How Do You Sleep?\" in the aftermath of Paul McCartney\\'s successful suit in'}, {'doc_id': 3373470, 'score': 70.17859, 'text': 'in the 2000 film \"Gimme Some Truth\" includes what authors Chip Madinger and Mark Easter describe as \"John\\'s query to Paul\", as Lennon faces the camera and sings: \"How do you sleep, ya cunt?\" Starr visited the studio during the recording of the song and was reportedly upset, saying: \"That\\'s enough, John.\" The final mix version as released on the album is in mono rather than stereo, unlike all the other tracks. In 2018 two versions of the original recording sessions were released as part of the Imagine box set in 5.1 surround sound. In a contemporary review of \"Imagine\",'}, {'doc_id': 10536294, 'score': 69.82143, 'text': 'Yatton Keynell Yatton Keynell (pronounced \"kennel\") is a village and civil parish in Wiltshire, England. The village is on the B4039 road near Castle Combe, about northwest of Chippenham, and about the same distance to the east of the county border with South Gloucestershire. The parish includes the hamlets of Broomfield, Giddeahall, Long Dean, Tiddleywink and West Yatton. The Bybrook River forms part of the western parish boundary. The economy of the parish was historically agricultural although it is now more of a residential area for surrounding towns; its population in the first census of 1801 was 353 and by'}]}]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "import jsonlines\n", "\n", "with jsonlines.open(\"./test.jsonl\", \"w\") as f:\n", " f.write_all(tmp)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "21015324" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 获取文件行数\n", "import os\n", "import mmap\n", "\n", "def file_len(fname):\n", " with open(fname, \"r+\") as f:\n", " buf = mmap.mmap(f.fileno(), 0)\n", " lines = 0\n", " while buf.readline():\n", " lines += 1\n", " return lines\n", "\n", "file_len(\"/share/ninglu_shao/data/Citation/psgs_w100.jsonl\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Dataset({\n", " features: ['id', 'text', 'title'],\n", " num_rows: 21015324\n", "})" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import datasets\n", "\n", "dataset = datasets.Dataset.from_pandas(df)\n", "\n", "dataset" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Found cached dataset json (/share/ninglu_shao/cache/json/default-62f749b1a8cc3230/0.0.0/8bb11242116d547c741b2e8a1f18598ffdd40a1d4f2a2872c7a28b697434bc96)\n", "100%|██████████| 1/1 [00:00<00:00, 292.71it/s]\n" ] }, { "data": { "text/plain": [ "DatasetDict({\n", " train: Dataset({\n", " features: ['a', 'b', 'c', 'd'],\n", " num_rows: 2\n", " })\n", "})" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tmp = datasets.load_dataset(\"json\", data_files=\"test.jsonl\", cache_dir=\"/share/ninglu_shao/cache\")\n", "\n", "tmp" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/share/ninglu_shao/envs/snl/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer\n", "\n", "class DprQueryEncoder:\n", " def __init__(self, model_name_or_path: str, cache_dir: str, device: str):\n", " self.device = device\n", " self.model = DPRQuestionEncoder.from_pretrained(\n", " model_name_or_path,\n", " cache_dir=cache_dir,\n", " )\n", " self.model.to(self.device)\n", " self.tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(\n", " model_name_or_path,\n", " cache_dir=cache_dir,\n", " )\n", " \n", " def encode(self, query: str):\n", " input_ids = self.tokenizer(query, return_tensors='pt')\n", " input_ids.to(self.device)\n", " embeddings = self.model(input_ids[\"input_ids\"]).pooler_output.detach().cpu().numpy()\n", " return embeddings # * (1, 768)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import jsonlines\n", "import faiss\n", "from dataclasses import dataclass\n", "from tqdm import tqdm\n", "\n", "\n", "import os\n", "import mmap\n", "\n", "def file_len(fname):\n", " with open(fname, \"r+\") as f:\n", " buf = mmap.mmap(f.fileno(), 0)\n", " lines = 0\n", " while buf.readline():\n", " lines += 1\n", " return lines\n", "\n", "\n", "@dataclass\n", "class DenseSearchResult:\n", " doc_id: int\n", " score: float\n", "\n", "\n", "class Searcher:\n", " def __init__(self, query_encoder: DprQueryEncoder, index_dir: str, doc_path: str):\n", " self.query_encoder = query_encoder\n", " self.index, self.doc_ids = self.load_index(index_dir)\n", " self.doc_list = self.load_doc_list(doc_path)\n", "\n", " def load_index(self, index_dir: str):\n", " index_path = os.path.join(index_dir, \"index\")\n", " doc_ids_path = os.path.join(index_dir, \"docid\")\n", " index = faiss.read_index(index_path)\n", " doc_ids = self.load_doc_ids(doc_ids_path)\n", " return index, doc_ids\n", "\n", " def load_doc_ids(self, doc_ids_path: str):\n", " with open(doc_ids_path, \"r\") as f:\n", " doc_ids = [line.rstrip() for line in f.readlines()]\n", " return doc_ids\n", "\n", " def load_doc_list(self, doc_path):\n", " lines = file_len(doc_path)\n", " \n", " doc_list = [None] # * 0 is not used\n", " with jsonlines.open(doc_path, \"r\") as f:\n", " for line in tqdm(f, desc=\"load doc list\", total=lines):\n", " doc_list.append(line)\n", " return doc_list\n", "\n", " def search(self, query: str, k: int):\n", " emb_q = self.query_encoder.encode(query)\n", " distances, indexes = self.index.search(emb_q, k)\n", " distances = distances.flat\n", " indexes = indexes.flat\n", " return [DenseSearchResult(idx, score)\n", " for score, idx in zip(distances, indexes) if idx != -1]\n", " \n", " def get_doc(self, doc_id: int):\n", " return self.doc_list[doc_id]" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import json\n", "\n", "\n", "with open(\"/share/ninglu_shao/code/ALCE/data/asqa_eval_dpr_top100.json\", \"r\") as f:\n", " tmp = json.load(f)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['qa_pairs', 'wikipages', 'annotations', 'sample_id', 'answer', 'question', 'docs'])" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tmp[0].keys()" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of the model checkpoint at facebook/dpr-question_encoder-single-nq-base were not used when initializing DPRQuestionEncoder: ['question_encoder.bert_model.pooler.dense.weight', 'question_encoder.bert_model.pooler.dense.bias']\n", "- This IS expected if you are initializing DPRQuestionEncoder from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n", "- This IS NOT expected if you are initializing DPRQuestionEncoder from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n", "load doc list: 100%|██████████| 21015324/21015324 [00:55<00:00, 377729.74it/s]\n" ] } ], "source": [ "query_encoder = DprQueryEncoder(\n", " model_name_or_path=\"facebook/dpr-question_encoder-single-nq-base\",\n", " cache_dir=\"/share/LMs\",\n", " device=\"cuda:0\",\n", ")\n", "\n", "searcher = Searcher(\n", " query_encoder=query_encoder,\n", " index_dir=\"/share/ninglu_shao/code/Citation/faiss.wikipedia-dpr-100w.dpr_single-nq.20200115.cd5034\",\n", " doc_path=\"/share/ninglu_shao/data/Citation/psgs_w100.jsonl\",\n", ")" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'id': 11,\n", " 'text': 'a skin disease (\"tzaraath\") that turned her skin white. Aaron pleaded with Moses to intercede for her, and Miriam, after seven days\\' quarantine, was healed. Aaron once again escaped any retribution. According to Numbers 16-17, a Levite named Korah led many in challenging Aaron\\'s exclusive claim to the priesthood. When the rebels were punished by being swallowed up by the earth (Numbers 16:25-35), Eleazar, the son of Aaron, was commissioned to take charge of the censers of the dead priests. And when a plague broke out among the people who had sympathized with the rebels, Aaron, at the command of',\n", " 'title': 'Aaron'}" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "searcher.get_doc(11)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ " >" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "searcher.index" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "results = searcher.search(\"What is the capital of France?\", 5)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "numpy.float32" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(results[0].score)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(results[0].doc_id.item())" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[DenseSearchResult(doc_id=8189129, score=85.7094),\n", " DenseSearchResult(doc_id=4532156, score=83.12891),\n", " DenseSearchResult(doc_id=8189084, score=82.94554),\n", " DenseSearchResult(doc_id=8189245, score=82.85818),\n", " DenseSearchResult(doc_id=4532102, score=82.65405)]" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[DenseSearchResult(idx, score)\n", "for score, idx in zip(result[0].flat, result[1].flat) if idx != -1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import faiss\n", "from transformers import DPRQuestionEncoder\n", "\n", "index = faiss.read_index(\"/share/ninglu_shao/code/Citation/faiss.wikipedia-dpr-100w.dpr_single-nq.20200115.cd5034/index\")\n", "index.search\n", "\n", "\n", "memory_long = []\n", "memory_short = []\n", "\n", "query_encoder = DPRQuestionEncoder.from_pretrained(\n", " \"facebook/dpr-question_encoder-single-nq-base\"\n", " cache_dir=\"/share/LMs\",\n", ")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# load json\n", "import json\n", "\n", "with open(\"/share/ninglu_shao/data/2WikiMultihopQA/test.json\", \"r\") as f:\n", " data = json.load(f)\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "import jsonlines\n", "\n", "with jsonlines.open(\"/share/ninglu_shao/data/Citation/2wiki.jsonl\", \"r\") as f:\n", " print(type(f))\n", " tmp = list(f)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "500" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(tmp)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b']" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from collections import OrderedDict\n", "\n", "a = OrderedDict()\n", "\n", "a[\"a\"] = 1\n", "a[\"b\"] = 2\n", "\n", "list(map(lambda x: x, a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# split" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/share/ninglu_shao/envs/snl/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "import datasets" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "DatasetDict({\n", " train: Dataset({\n", " features: ['text', 'embedding'],\n", " num_rows: 4000000\n", " })\n", " valid: Dataset({\n", " features: ['text', 'embedding'],\n", " num_rows: 5000\n", " })\n", " test: Dataset({\n", " features: ['text', 'embedding'],\n", " num_rows: 5000\n", " })\n", "})" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dataset = datasets.load_from_disk(\"/share/ninglu_shao/data/EmbedPrivacy/e5-large-v2/wikipedia\")\n", "\n", "dataset" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "prompt_list = []\n", "\n", "for data in dataset[\"test\"]:\n", " text = data[\"text\"]\n", " prompt = f\"Instruction: While keeping the semantics unchanged, expand the following content to about 60 words.\\nInput: {text}\\nOutput:\"\n", " prompt_list.append(prompt)" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 5/5 [00:27<00:00, 5.49s/it]\n" ] } ], "source": [ "import os\n", "import openai\n", "from tqdm import trange\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"\n", "\n", "\n", "openai.api_key = \"sk-I4oVv5Q9pJ3YIKMl70213533B2Ef4b218cBdB8D58b05A47a\"\n", "openai.base_url = \"https://chatapi.onechat.fun/v1/\"\n", "\n", "fail_id_list = []\n", "result = []\n", "\n", "for i in trange(len(prompt_list)):\n", " try:\n", " prompt = prompt_list[i]\n", " response = openai.chat.completions.create(\n", " model=\"gpt-4\", # 确认使用 GPT-4 模型\n", " response_format={ \"type\": \"json_object\" },\n", " seed=2023,\n", " temperature=1.0,\n", " top_p=1.0,\n", " max_tokens=100,\n", " messages=[\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", " )\n", " result.append({\n", " \"idx\": i,\n", " \"content\": response.choices[0].message.content\n", " })\n", " except:\n", " fail_id_list.append({\n", " \"idx\": i,\n", " \"response\": response,\n", " })" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "100%|██████████| 5/5 [00:25<00:00, 5.17s/it]\n" ] } ], "source": [ "import os\n", "import openai\n", "from tqdm import trange\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"\n", "\n", "\n", "openai.api_key = \"sk-I4oVv5Q9pJ3YIKMl70213533B2Ef4b218cBdB8D58b05A47a\"\n", "openai.base_url = \"https://gpts.onechat.fun/v1/\"\n", "\n", "fail_id_list = []\n", "result = []\n", "\n", "for i in trange(len(prompt_list)):\n", " try:\n", " prompt = prompt_list[i]\n", " response = openai.chat.completions.create(\n", " model=\"gpt-4\", # 确认使用 GPT-4 模型\n", " seed=2023,\n", " temperature=1.0,\n", " top_p=1.0,\n", " # max_tokens=100,\n", " messages=[\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", " )\n", " result.append({\n", " \"idx\": i,\n", " \"content\": response.choices[0].message.content\n", " })\n", " except:\n", " fail_id_list.append({\n", " \"idx\": i,\n", " \"response\": response,\n", " })\n", "\n", "import pickle\n", "\n", "with open(\"/share/ninglu_shao/code/EmbedPrivacy/60.data\", \"wb\") as f:\n", " pickle.dump(result, f)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "old_fail_id_list = [x[\"idx\"] for x in fail_id_list]\n", "fail_id_list = []\n", "\n", "for i in trange(len(prompt_list)):\n", " if i not in old_fail_id_list:\n", " continue\n", " try:\n", " prompt = prompt_list[i]\n", " response = openai.chat.completions.create(\n", " model=\"gpt-4\", # 确认使用 GPT-4 模型\n", " seed=2023,\n", " temperature=1.0,\n", " top_p=1.0,\n", " # max_tokens=100,\n", " messages=[\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", " )\n", " result.append({\n", " \"idx\": i,\n", " \"content\": response.choices[0].message.content\n", " })\n", " except:\n", " fail_id_list.append({\n", " \"idx\": i,\n", " \"response\": response,\n", " })\n", "\n", "import pickle\n", "\n", "with open(\"/share/ninglu_shao/code/EmbedPrivacy/60.data\", \"wb\") as f:\n", " pickle.dump(result, f)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "82" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(result[0][\"content\"].split())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import openai\n", "from tqdm import trange\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"\n", "\n", "\n", "openai.api_key = \"sk-I4oVv5Q9pJ3YIKMl70213533B2Ef4b218cBdB8D58b05A47a\"\n", "openai.base_url = \"https://gpts.onechat.fun/v1/\"\n", "\n", "old_fail_id_list = [x[\"idx\"] for x in fail_id_list]\n", "fail_id_list = []\n", "\n", "for i in trange(len(prompt_list)):\n", " if i not in old_fail_id_list:\n", " continue\n", " try:\n", " prompt = prompt_list[i]\n", " response = openai.chat.completions.create(\n", " model=\"gpt-4\", # 确认使用 GPT-4 模型\n", " seed=2023,\n", " temperature=1.0,\n", " top_p=1.0,\n", " # max_tokens=100,\n", " messages=[\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", " )\n", " result.append({\n", " \"idx\": i,\n", " \"content\": response.choices[0].message.content\n", " })\n", " except:\n", " fail_id_list.append({\n", " \"idx\": i,\n", " \"response\": response,\n", " })" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import openai\n", "from tqdm import trange\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"\n", "\n", "\n", "openai.api_key = \"sk-I4oVv5Q9pJ3YIKMl70213533B2Ef4b218cBdB8D58b05A47a\"\n", "openai.base_url = \"https://gpts.onechat.fun/v1/\"\n", "\n", "\n", "for _ in range(4):\n", " old_fail_id_list = [x[\"idx\"] for x in fail_id_list]\n", " fail_id_list = []\n", "\n", " for i in trange(len(prompt_list)):\n", " if i not in old_fail_id_list:\n", " continue\n", " try:\n", " prompt = prompt_list[i]\n", " response = openai.chat.completions.create(\n", " model=\"gpt-4\", # 确认使用 GPT-4 模型\n", " seed=2023,\n", " temperature=1.0,\n", " top_p=1.0,\n", " max_tokens=100,\n", " messages=[\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", " )\n", " result.append({\n", " \"idx\": i,\n", " \"content\": response.choices[0].message.content\n", " })\n", " except:\n", " fail_id_list.append({\n", " \"idx\": i,\n", " \"response\": response,\n", " })" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[{'idx': 0,\n", " 'content': 'The name was given by the Falkland Islands Dependencies Survey (FIDS) in honour of Gunther Böhnecke, a renowned German oceanographer. Böhnecke was a key member of the German scientific expedition aboard the ship Meteor, which conducted research from 1925 to 1927.'},\n", " {'idx': 1,\n", " 'content': \"In the year 2015, the group known as the MYWP made a significant contribution to historical literature by publishing a comprehensive book. The work, which is titled 'Killing Sites – Research and Remembrance', serves as an influential source for scholars and enthusiasts alike.\"},\n", " {'idx': 2,\n", " 'content': 'The broadcasting station made a decision to transition their programming. They chose to lean towards a show that incorporates a more extensive use of music. This indicates a shift in their focus and an aim to connect with a different audience.'},\n", " {'idx': 3,\n", " 'content': 'By the time the 17th century was drawing to a close, Irkutsk had begun to grow beyond being just a humble settlement, transforming into a small yet bustling town. Not just that, signs of expanding civilization in the form of constructing monasteries were also evident. Outskirts of the town had also started seeing a fair bit of development with suburbs coming into existence and agricultural settlements beginning to form, speaking volumes about the latent progress.'},\n", " {'idx': 4,\n", " 'content': 'The overexpression of Nov in transgenic mice, specifically within osteoblasts, has been found to antagonize two key signaling pathways - the Bone Morphogenetic Protein (BMP) and Wnt-signaling. This overexpression and subsequent antagonism ultimately lead to the development of osteopenia in these mice.'}]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import os\n", "import openai\n", "import time\n", "from tqdm import trange\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"\n", "\n", "\n", "openai.api_key = \"sk-I4oVv5Q9pJ3YIKMl70213533B2Ef4b218cBdB8D58b05A47a\"\n", "openai.base_url = \"https://gpts.onechat.fun/v1/\"\n", "\n", "fail_id_list = []\n", "result = []\n", "\n", "for i in trange(len(prompt_list[5:10])):\n", " try:\n", " prompt = prompt_list[i]\n", " response = openai.chat.completions.create(\n", " model=\"gpt-4\", # 确认使用 GPT-4 模型\n", " response_format={ \"type\": \"json_object\" },\n", " seed=2023,\n", " temperature=1.0,\n", " top_p=1.0,\n", " # max_tokens=100,\n", " messages=[\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", " )\n", " result.append({\n", " \"idx\": i,\n", " \"content\": response.choices[0].message.content\n", " })\n", " except:\n", " fail_id_list.append({\n", " \"idx\": i,\n", " \"response\": response,\n", " })\n", " time.sleep(1)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fail_id_list" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ChatCompletion(id='', choices=None, created=0, model='gpt-4', object='chat.completion', system_fingerprint=None, usage=CompletionUsage(completion_tokens=0, prompt_tokens=0, total_tokens=0))\n" ] } ], "source": [ "import os\n", "import openai\n", "os.environ[\"http_proxy\"] = \"http://127.0.0.1:15777\"\n", "os.environ[\"https_proxy\"] = \"http://127.0.0.1:15777\"\n", "\n", "def query_gpt4(question):\n", " openai.api_key = \"sk-I4oVv5Q9pJ3YIKMl70213533B2Ef4b218cBdB8D58b05A47a\"\n", " openai.base_url = \"https://chatapi.onechat.fun/v1/\"\n", " try:\n", " response = openai.chat.completions.create(\n", " model=\"gpt-4\", # 确认使用 GPT-4 模型\n", " # response_format={\"type\": \"json_object\"},\n", " seed=2023,\n", " temperature=1.0,\n", " top_p=1.0,\n", " # max_tokens=200,\n", " messages=[\n", " {\"role\": \"user\", \"content\": prompt},\n", " ]\n", " )\n", " # print(response)\n", " return response\n", " except Exception as e:\n", " return str(e)\n", "\n", "# 问题\n", "question = \"为什么太阳那么红?\"\n", "\n", "# 获取并打印回答\n", "answer = query_gpt4(question)\n", "print(answer)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'ChatCompletion' object is not subscriptable", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m/share/ninglu_shao/code/Citation/test.ipynb 单元格 10\u001b[0m line \u001b[0;36m1\n\u001b[0;32m----> 1\u001b[0m answer[\u001b[39m'\u001b[39;49m\u001b[39mchoices\u001b[39;49m\u001b[39m'\u001b[39;49m][\u001b[39m0\u001b[39m]\u001b[39m.\u001b[39mmessage[\u001b[39m'\u001b[39m\u001b[39mcontent\u001b[39m\u001b[39m'\u001b[39m]\n", "\u001b[0;31mTypeError\u001b[0m: 'ChatCompletion' object is not subscriptable" ] } ], "source": [ "answer['choices'][0].message['content']" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 4, 5, 6, 7]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import re\n", "\n", "sent = \"The [1] quick [2] brown [3] fox [4] jumps [5] over [6] the [7] lazy [8] dog.\"\n", "[int(r[1:])-1 for r in re.findall(r\"\\[\\d+\", sent)]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1\n", "[2\n", "[3\n", "[4\n", "[5\n", "[6\n", "[7\n", "[8\n" ] } ], "source": [ "for r in re.findall(r\"\\[\\d+\", sent):\n", " print(r)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 2 }